NET流行高效能JSON框架-Json.NET
阿新 • • 發佈:2020-10-10
在日常程式設計中經常會使用到Json來進行資料的互動好在.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 = "[email protected]", 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": "[email protected]",// "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>[email protected]</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