Json.Net安装使用参考文档:https://www.cjavapy.com/article/174/
1、使用LINQ for JSON
JObject o = JObject.Parse(@"{
'CPU': 'Intel',
'Drives': [
'DVD read/writer',
'500 gigabyte hard drive'
]
}");
string cpu = (string)o["CPU"];
// Intel
string firstDrive = (string)o["Drives"][0];
// DVD read/writer
IList<string> allDrives = o["Drives"].Select(t => (string)t).ToList();
// DVD read/writer
// 500 gigabyte hard drive
2、解析JSON
1)解析JSON文本
可以使用Parse(string)从字符串读取JSON值。
string json = @"{
CPU: 'Intel',
Drives: [
'DVD read/writer',
'500 gigabyte hard drive'
]
}";
JObject o = JObject.Parse(json);
string json = @"[
'Small',
'Medium',
'Large'
]";
JArray a = JArray.Parse(json);
2)从文件加载JSON
using (StreamReader reader = File.OpenText(@"c:\person.json"))
{
JObject o = (JObject)JToken.ReadFrom(new JsonTextReader(reader));
// do stuff
}
3、创建JSON
1)手动创建JSON
一次设置一个值并创建一个对象和数组可以让您完全控制,但是它比其他选项更冗长。
JArray array = new JArray();
JValue text = new JValue("Manual text");
JValue date = new JValue(new DateTime(2000, 5, 23));
array.Add(text);
array.Add(date);
string json = array.ToString();
// [
// "Manual text",
// "2000-05-23T00:00:00"
// ]
2)用LINQ创建JSON
使用LINQ声明性地创建JSON对象是一种从值集合创建JSON的快速方法。
List<Post> posts = GetPosts();
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());
//{
// "channel": {
// "title": "James Newton-King",
// "link": "http://james.newtonking.com",
// "description": "James Newton-King\'s blog.",
// "item": [
// {
// "title": "Json.NET 1.3 + New license + Now on CodePlex",
// "description": "Announcing the release of Json.NET 1.3, the MIT license and being available on CodePlex",
// "link": "http://james.newtonking.com/projects/json-net.aspx",
// "category": [
// "Json.NET",
// "CodePlex"
// ]
// },
// {
// "title": "LINQ to JSON beta",
// "description": "Announcing LINQ to JSON",
// "link": "http://james.newtonking.com/projects/json-net.aspx",
// "category": [
// "Json.NET",
// "LINQ"
// ]
// }
// ]
// }
//}
3)通过object创建JSON
最后一个选项是使用FromObject()方法从非JSON类型创建JSON对象。在内部,FromObject将使用JsonSerializer将对象序列化为LINQ到JSON对象,而不是文本。
下面的示例展示了如何从匿名对象创建JSON对象,但是任何.net类型都可以与FromObject一起用于创建JSON。
JObject o = JObject.FromObject(new
{
channel = new
{
title = "James Newton-King",
link = "http://james.newtonking.com",
description = "James Newton-King's blog.",
item =
from p in posts
orderby p.Title
select new
{
title = p.Title,
description = p.Description,
link = p.Link,
category = p.Categories
}
}
});