json for .net(二)开源的Json.Net库

来源:互联网 发布:淘宝配眼镜可以退吗 编辑:程序博客网 时间:2024/05/13 06:59

使用Newtonsoft.Json这是一个开源的Json.Net库。

下载地址:http://json.codeplex.com/releases/view/50552。当前版本为 Release 8

从下载到的源代码中获取相应版本的Newtonsoft.Json.Net.dll,添加到自己的工程中。

using Newtonsoft.Json;

定义类:    public class Message    {        public string Address { get; set; }        [JsonProperty(TypeNameHandling = TypeNameHandling.All)]        public object Body { get; set; }    }    public class SearchDetails    {        public string Query { get; set; }        public string Language { get; set; }    }测试:            Message message = new Message            {                Address = "http://google.com",                Body = new SearchDetails { Query = "Json.Net", Language = "en-us" }            };            string jsonMsg = JsonConvert.SerializeObject(message, Formatting.Indented);//Indented表示以缩进形式显示结果              System.Diagnostics.Debug.Write(jsonMsg);            Message deserialized = JsonConvert.DeserializeObject<Message>(jsonMsg);            SearchDetails searchDetails = (SearchDetails)deserialized.Body;            Response.Write(searchDetails.Query + "," + searchDetails.Language + "<br/>");Debug输出结果格式:{    "Address": "http://google.com",    "Body": {    "$type": "TestJsonSerialization.SearchDetails, TestJsonSerialization",    "Query": "Json.Net",    "Language": "en-us"}}


注:1.JsonProperty标记字段或属性,用来控制它作为一个Json对象的属性序列化。

       2.TypeNameHandling 用来为Json序列化指定类型名。它有几个枚举值:

MemberDescriptionNoneDo not include the .NET type name when serializing types.
ObjectsInclude the .NET type name when serializing into a JSON object structure.
ArraysInclude the .NET type name when serializing into a JSON array structure.
AutoInclude the .NET type name when the type of the object being serialized is not the same as its declared type.
AllAlways include the .NET type name when serializing.


 Json.net/Newtonsoft 3.0 新特性JObject/Linq to Json

 

在反序列化时并没有预先定义好的类也可用Newtonsoft实现,甚至还提供了Json的Linq查询

 

JObject

1.Json是这样的

{title:123,body:456,list:{title:'这是一个标题',body:'what'}}

2.我要将其中几项都搞出来,代码:

static void Main(string[] args){string str = "{title:123,body:456,list:{title:'这是一个标题',body:'what'}}";JObject o = JObject.Parse(str);Console.WriteLine(o["title"]);Console.WriteLine(o["body"]);Console.WriteLine(o["list"]["title"]);Console.WriteLine(o["list"]["body"]);Console.ReadKey();}

3.这样就输出了:
123
456
"这是一个标题"
"what"

不足:字符串还是案字符串输出带"",但我想这也不是问题.Trim就好了

Linq to Json

基本Linq的都差不多,可以参考Json.net文档.

using Newtonsoft.Json.Linq;

定义类:    public class Product    {        public string Name { get; set; }        public DateTime Expiry { get; set; }        public decimal Price { get; set; }        public string[] Sizes { get; set; }    }测试:            Product product = new Product            {                Name = "Apple",                Expiry = new DateTime(2010, 12, 18),                Price = 3.99M,                Sizes = new string[] { "Small", "Medium", "Large" }            };            string serializedJson = JsonConvert.SerializeObject(product);            JObject o = JObject.Parse(serializedJson);            string name = (string)o["Name"];            //Apple            JArray sizes = (JArray)o["Sizes"];            string smallest = (string)sizes[0];            Response.Write(name + "," + smallest + "<br/>");//输出Small            //SelectToken            smallest = (string)o.SelectToken("Sizes[0]");            Response.Write(smallest + "<br/>");//输出Small            //SelectToken with Linq            var sizeLen5 = o["Sizes"].Select(i => (string)i).Where(i => i.Length == 5).ToList<string>();           foreach (var size in sizeLen5)            {                Response.Write((string)size+ " <br/>");            };//输出Small和Large


注:JArray表示一个Json集合,JObject表示一个Json对象。

 

原创粉丝点击