相关文章推荐
有腹肌的油条  ·  C++ ...·  15 分钟前    · 
气势凌人的牛腩  ·  气轻PyQt5 02 ...·  4 月前    · 
稳重的刺猬  ·  初识openmp ...·  6 月前    · 
神勇威武的山羊  ·  mysql ...·  8 月前    · 

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

//把 Json 字符串反序列化为对象
目标对象 = JsonConvert.DeserializeObject(JSON字符串, typeof (目标对象));
//把目标对象序列化为 Json 字符串

string Json字符串 = JsonConvert.SerializeObject(目标对象);


1 . 引用Newtonsoft.Json.dll
2.在项目中添加引用..
序列化和反序列在.net项目中:

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string output = JsonConvert.SerializeObject(product);
//  "Name": "Apple",
//  "Expiry": new Date(1230422400000),
//  "Price": 3.99,
//  "Sizes": [
//     "Small",
//     "Medium",
//     "Large"
//  ]
Product deserializedProduct = (Product)JsonConvert.DeserializeObject(output, typeof(Product));


读取JSON

string jsonText = "['JSON!',1,true,{property:'value'}]";
JsonReader reader = new JsonReader(new StringReader(jsonText));
Console.WriteLine("TokenType\t\tValueType\t\tValue");
while (reader.Read())
     Console.WriteLine(reader.TokenType + "\t\t" + WriteValue(reader.ValueType) + "\t\t" + WriteValue(reader.Value))


结果显示:

TokenTypeValueTypeValue StartArray String System.String JSON! Integer System.Int32 Boolean System.Boolean StartObject PropertyName System.String property String System.String value EndObject EndArray

JSON写入

StringWriter sw = new StringWriter();
JsonWriter writer = new JsonTextWriter(sw);
writer.WriteStartArray();
writer.WriteValue("JSON!");
writer.WriteValue(1);
writer.WriteValue(true);
writer.WriteStartObject();
writer.WritePropertyName("property");
writer.WriteValue("value");
writer.WriteEndObject();
writer.WriteEndArray();
writer.Flush();
string jsonText = sw.GetStringBuilder().ToString();
Console.WriteLine(jsonText);
// ['JSON!',1,true,{property:'value'}]
//把datatable转换成json格式 
public string GetAllCategory()   
{       
    string result = "";  
    DataTable dt= catDAO.GetAllCategory();  
    result=JsonConvert.SerializeObject(dt, new DataTableConverter());  
    return result;