NET流行高性能JSON框架之Json.NET
本文轉載自微信公眾號「UP技術控」,作者conan5566。轉載本文請聯(lián)系UP技術控公眾號。
在日常編程中經常會使用到Json來進行數(shù)據(jù)的交互好在.Net平臺下有很多開源的Json庫使得我們能夠比較輕松快速的處理各種復雜的Json,其中Newtonsoft庫
是NET的流行高性能JSON框架
特性
工具
VS2010+
Newtonsoft庫
從NuGet下載合適的Newtonsoft.Json庫
1.在你需要引用Newtosoft.Json的項目上,點擊鼠標右鍵,管理Nuget程序包即可打開項目包管理器。
2.在包管理器中輸入關鍵字"Json"看到Newtosoft.Json這個庫 點擊右下加的箭頭即可完成安裝。
示例
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