Newtonsoft.Json序列化和反序列

weixin_30924079發表於2015-03-23

(轉自:http://www.cnblogs.com/sbxwylt/archive/2008/12/31/1366199.html)

這裡下載:http://www.newtonsoft.com/products/json/
安裝:
   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 = javascriptConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "Expiry": new Date(1230422400000),
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//} 
Product deserializedProduct = (Product)javascriptConvert.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 null null
String System.String JSON!
Integer System.Int32 1
Boolean System.Boolean True
StartObject null null
PropertyName System.String property
String System.String value
EndObject null null
EndArray null null

JSON寫入

StringWriter sw = new StringWriter();
JsonWriter writer = new JsonWriter(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'}]


這裡會列印出: ['JSON!',1,true,{property:'value'}].

轉載於:https://www.cnblogs.com/FindSelf/p/3738775.html

相關文章