安装:
1.解压下载文件,得到Newtonsoft.Json.dll
2.在项目中添加引用..
序列化和反序列在.net项目中:
1 |
Product product = new Product(); |
1 |
1 |
product.Name = "Apple"; |
1 |
product.Expiry = new DateTime(2008, 12, 28); |
1 |
product.Price = 3.99M; |
1 |
product.Sizes = new string[] { "Small", "Medium", "Large" }; |
1 |
1 |
string output = javascriptConvert.SerializeObject(product); |
1 |
//{ |
1 |
// "Name": "Apple", |
1 |
// "Expiry": new Date(1230422400000), |
1 |
// "Price": 3.99, |
1 |
// "Sizes": [ |
1 |
// "Small", |
1 |
// "Medium", |
1 |
// "Large" |
1 |
// ] |
1 |
//} |
1 |
1 |
Product deserializedProduct = (Product)javascriptConvert.DeserializeObject(output, typeof(Product)); |
读取JSON
1 |
string jsonText = "['JSON!',1,true,{property:'value'}]"; |
1 |
1 |
JsonReader reader = new JsonReader(new StringReader(jsonText)); |
1 |
1 |
Console.WriteLine("TokenType\t\tValueType\t\tValue"); |
1 |
1 |
while (reader.Read()) |
1 |
{ |
1 |
Console.WriteLine(reader.TokenType + "\t\t" + WriteValue(reader.ValueType) + "\t\t" + WriteValue(reader.Value)) |
1 |
} |
结果显示:
TokenType | ValueType | Value |
---|---|---|
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 |
1 |
StringWriter sw = new StringWriter(); |
1 |
JsonWriter writer = new JsonWriter(sw); |
1 |
1 |
writer.WriteStartArray(); |
1 |
writer.WriteValue("JSON!"); |
1 |
writer.WriteValue(1); |
1 |
writer.WriteValue(true); |
1 |
writer.WriteStartObject(); |
1 |
writer.WritePropertyName("property"); |
1 |
writer.WriteValue("value"); |
1 |
writer.WriteEndObject(); |
1 |
writer.WriteEndArray(); |
1 |
1 |
writer.Flush(); |
1 |
1 |
string jsonText = sw.GetStringBuilder().ToString(); |
1 |
1 |
Console.WriteLine(jsonText); |
1 |
// ['JSON!',1,true,{property:'value'}] |
这里会打印出: ['JSON!',1,true,{property:'value'}]
.
原文:http://www.cnblogs.com/sbxwylt/archive/2008/12/31/1366199.html