json.net

前端之家收集整理的这篇文章主要介绍了json.net前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

json.net 是一个用C#写的Json的操作类库,可以在http://json.codeplex.com/ 下载

对象序列化为json字符串

public class Product { public string Name { get; set; } public DateTime Expiry { get; set; } public decimal Price { get; set;} public string[] Sizes { get; set; } } static void Main(string[] args) { Product product = new Product() { Name ="android",Expiry =new DateTime (),Price =2000,Sizes =new  string[]{"1.5","2.2","4.1"} }; Console.WriteLine(JsonConvert.SerializeObject(product)); Console.Read(); }

输出

{"Name":"android","Expiry":"\/Date(-62135596800000 0800)\/","Price":2000.0,"Size
s":["1.5","2.2","4.1"]}

设置时间类型的格式 两个用来序列化时间的对象IsoDateTimeConverter JavaScriptDateTimeConverter

Console.WriteLine(JsonConvert .SerializeObject (product,new IsoDateTimeConverter())); Console.WriteLine(JsonConvert.SerializeObject(product,new JavaScriptDateTimeConverter()));

输出

{"Name":"android","Expiry":"2000-09-09T00:00:00","Sizes":["1.5"," 2.2","4.1"]}
{"Name":"android","Expiry":new Date(968428800000),"Sizes":["1.5","2.2","4.1"]}

自定义输出时间格式

IsoDateTimeConverter iso = new IsoDateTimeConverter(); iso.DateTimeFormat = "yyyy-MM-dd";//设置事件的格式
 Console.WriteLine(JsonConvert.SerializeObject(product,iso));

输出

{"Name":"android","Expiry":"2000-09-09","4.1 "]}

反序列化

Product p=(Product)JsonConvert.DeserializeObject(str,typeof(Product));

创建Jobject对象

JObject RSS =
  new JObject( new JProperty("channel",new JObject( new JProperty("title","James Newton-King"),new JProperty("link","http://james.newtonking.com"),new JProperty("description","James Newton-King's blog."),new JProperty("item",new JArray( from p in posts orderby p.Title select new JObject( new JProperty("title",p.Title),new JProperty("description",p.Description),new JProperty("link",p.Link),new JProperty("category",new JArray( from c in p.Categories select new JValue(c))))))))); Console.WriteLine(RSS.ToString());

直接用对象创建Jobject对象

JObject obj = JObject.FromObject(new Product() { Name = "android",Expiry = new DateTime(2000,9,9),Price = 2000,Sizes = new string[] { "1.5","4.1" } });

猜你在找的Json相关文章