在.NET中使用Newtonsoft.Json转换,读取,写入
发布时间:2020-12-16 19:59:26 所属栏目:百科 来源:网络整理
导读:using Newtonsoft.Json; using Newtonsoft.Json.Converters; //把 Json 字符串反序列化为对象 目标对象= JavaScriptConvert.DeserializeObject(JSON字符串, typeof (目标对象)); //把目标对象序列化为 Json 字符串 string Json 字符串 = JavaScriptConvert .
using
Newtonsoft.Json;
http://www.cnblogs.com/gghxh/archive/2008/01/11/1035482.html using Newtonsoft.Json.Converters; //把Json字符串反序列化为对象 目标对象= JavaScriptConvert.DeserializeObject(JSON字符串,typeof (目标对象)); //把目标对象序列化为Json字符串 string Json字符串 = JavaScriptConvert.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 = 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)) } 结果显示:
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!',{property:'value'}]
转贴自:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |