.NET流行高性能JSON框架-Json.NET

在日常编程中经常会使用到Json来进行数据的交互好在.Net平台下有很多开源的Json库使得我们能够比较轻松快速的处理各种复杂的Json,其中Newtonsoft库

是NET的流行高性能JSON框架.

特性

.NET流行高性能JSON框架-Json.NET

工具

VS2010+

Newtonsoft库

从NuGet下载合适的Newtonsoft.Json库

1.在你需要引用Newtosoft.Json的项目上,点击鼠标右键,管理Nuget程序包即可打开项目包管理器。

2.在包管理器中输入关键字"Json"看到Newtosoft.Json这个库 点击右下加的箭头即可完成安装。

.NET流行高性能JSON框架-Json.NET

示例

1、序列化JSON-序列化和反序列化JSON,序列化程序设置和序列化属性

public class Account{    public string Email { get; set; }    public bool Active { get; set; }    public DateTime CreatedDate { get; set; }    public IList<string> Roles { get; set; }}
Account account = new Account{    Email = "james@example.com",    Active = true,    CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),    Roles = new List<string>    {        "User",        "Admin"    }};
string json = JsonConvert.SerializeObject(account, Formatting.Indented);// {//   "Email": "james@example.com",//   "Active": true,//   "CreatedDate": "2013-01-20T00:00:00Z",//   "Roles": [//     "User",//     "Admin"//   ]// }
Console.WriteLine(json);

2、LINQ to JSON-解析,查询,修改和编写JSON

JArray array = new JArray();array.Add("Manual text");array.Add(new DateTime(2000, 5, 23));
JObject o = new JObject();o["MyArray"] = array;
string json = o.ToString();// {//   "MyArray": [//     "Manual text",//     "2000-05-23T00:00:00"//   ]// }

3、JSON模式-加载模式并验证JSON。请注意,JSON Schema验证已移至其自己的程序包。有关 更多详细信息,请参见https://www.newtonsoft.com/jsonschema。

JObject o = JObject.Parse(@"{  'Stores': [    'Lambton Quay',    'Willis Street'  ],  'Manufacturers': [    {      'Name': 'Acme Co',      'Products': [        {          'Name': 'Anvil',          'Price': 50        }      ]    },    {      'Name': 'Contoso',      'Products': [        {          'Name': 'Elbow Grease',          'Price': 99.95        },        {          'Name': 'Headlight Fluid',          'Price': 4        }      ]    }  ]}");
string name = (string)o.SelectToken("Manufacturers[0].Name");
Console.WriteLine(name);// Acme Co
decimal productPrice = (decimal)o.SelectToken("Manufacturers[0].Products[0].Price");
Console.WriteLine(productPrice);// 50
string productName = (string)o.SelectToken("Manufacturers[1].Products[0].Name");
Console.WriteLine(productName);// Elbow Grease

4、转换XML-将JSON转换为XML和XML转换为JSON

string json = @"{  '@Id': 1,  'Email': 'james@example.com',  'Active': true,  'CreatedDate': '2013-01-20T00:00:00Z',  'Roles': [    'User',    'Admin'  ],  'Team': {    '@Id': 2,    'Name': 'Software Developers',    'Description': 'Creators of fine software products and services.'  }}";
XNode node = JsonConvert.DeserializeXNode(json, "Root");
Console.WriteLine(node.ToString());// <Root Id="1">//   <Email>james@example.com</Email>//   <Active>true</Active>//   <CreatedDate>2013-01-20T00:00:00Z</CreatedDate>//   <Roles>User</Roles>//   <Roles>Admin</Roles>//   <Team Id="2">//     <Name>Software Developers</Name>//     <Description>Creators of fine software products and services.</Description>//   </Team>// </Root>

5、BSON-序列化和反序列化BSON

public class Event{    public string Name { get; set; }    public DateTime StartDate { get; set; }}
Event e = new Event{    Name = "Movie Premiere",    StartDate = new DateTime(2013, 1, 22, 20, 30, 0, DateTimeKind.Utc)};
MemoryStream ms = new MemoryStream();using (BsonWriter writer = new BsonWriter(ms)){    JsonSerializer serializer = new JsonSerializer();    serializer.Serialize(writer, e);}
string data = Convert.ToBase64String(ms.ToArray());
Console.WriteLine(data);// MQAAAAJOYW1lAA8AAABNb3ZpZSBQcmVtaWVyZQAJU3RhcnREYXRlAED982M8AQAAAA==

6、读取和写入JSON-使用JsonTextReader读取JSON,使用JsonTextWriter写入JSON

string json = @"{   'CPU': 'Intel',   'PSU': '500W',   'Drives': [     'DVD read/writer'     /*(broken)*/,     '500 gigabyte hard drive',     '200 gigabyte hard drive'   ]}";
JsonTextReader reader = new JsonTextReader(new StringReader(json));while (reader.Read()){    if (reader.Value != null)    {        Console.WriteLine("Token: {0}, Value: {1}", reader.TokenType, reader.Value);    }    else    {        Console.WriteLine("Token: {0}", reader.TokenType);    }}
// Token: StartObject// Token: PropertyName, Value: CPU// Token: String, Value: Intel// Token: PropertyName, Value: PSU// Token: String, Value: 500W// Token: PropertyName, Value: Drives// Token: StartArray// Token: String, Value: DVD read/writer// Token: Comment, Value: (broken)// Token: String, Value: 500 gigabyte hard drive// Token: String, Value: 200 gigabyte hard drive// Token: EndArray// Token: EndObject

更多功能见https://github.com/JamesNK/Newtonsoft.Json