在.NET中使用Newtonsoft.Json转换,读取,写入
2013-07-11 14:53
513 查看
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
//把Json字符串反序列化为对象
目标对象 =JavaScriptConvert.DeserializeObject(JSON字符串, typeof(目标对象));
//把目标对象序列化为Json字符串
stringJson字符串=JavaScriptConvert.SerializeObject(目标对象);
1.引用Newtonsoft.Json.dll
2.在项目中添加引用..
序列化和反序列在.net项目中:
Productproduct=newProduct();
product.Name="Apple";
product.Expiry=newDateTime(2008,12,28);
product.Price=3.99M;
product.Sizes=newstring[]{"Small","Medium","Large"};
stringoutput=JavaScriptConvert.SerializeObject(product);
//{
//"Name":"Apple",
//"Expiry":newDate(1230422400000),
//"Price":3.99,
//"Sizes":[
// "Small",
// "Medium",
// "Large"
//]
//}
ProductdeserializedProduct=(Product)JavaScriptConvert.DeserializeObject(output,typeof(Product));
读取JSON
stringjsonText="['JSON!',1,true,{property:'value'}]";
JsonReaderreader=newJsonReader(newStringReader(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))
}
结果显示:
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 |
JSON写入
StringWritersw=newStringWriter();
JsonWriterwriter=newJsonWriter(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();
stringjsonText=sw.GetStringBuilder().ToString();
Console.WriteLine(jsonText);
//['JSON!',1,true,{property:'value'}]
相关文章推荐
- 在.NET中使用Newtonsoft.Json转换,读取,写入
- 在.NET中使用Newtonsoft.Json转换,读取,写入的方法介绍
- 在.NET中使用Newtonsoft.Json转换,读取,写入.
- 在.NET中使用Newtonsoft.Json转换,读取,写入
- 在.NET中使用Newtonsoft.Json转换,读取,写入
- 在.NET中使用Newtonsoft.Json转换,读取,写入
- 在.NET中使用Newtonsoft.Json转换,读取,写入
- 在.NET中使用Newtonsoft.Json转换,读取,写入
- 在.NET中使用Newtonsoft.Json转换,读取,写入
- 在.NET中使用Newtonsoft.Json转换,读取,写入
- 在.NET中使用Newtonsoft.Json转换,读取,写入.
- 在.NET中使用Newtonsoft.Json转换,读取,写入的方法介绍
- Asp.Net中使用Newtonsoft.Json转换,读取,写入
- Asp.Net中使用Newtonsoft.Json转换,读取,写入
- 在.NET使用Newtonsoft.Json转换,读取,写入json
- c# 在.NET使用Newtonsoft.Json转换,读取,写入json
- .NET json格式 使用Newtonsoft.Json.JsonConvert类 附读取文件方法
- 在.NET使用Newtonsoft.Json转换,读取,写入json