开发手册 欢迎您!
软件开发者资料库

.NET(C#) Json.Net(newtonsoft)操作处理(解析)JSON数据(LINQ to JSON)

本文主要介绍通过LINQ的语法使用Json.Net(newtonsoft)库进行Json数据的序列化和反序列化。LINQ to JSON是一个用于处理JSON对象的API。它在设计时考虑到了LINQ,以支持快速查询和创建JSON对象。LINQ to JSON位于Newtonsoft.Json.Linq命名空间。

Json.Net安装使用参考文档https://www.wonhero.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"];// Intelstring firstDrive = (string)o["Drives"][0];// DVD read/writerIList 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 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
}
}
});