Json.NET APILinq to Json

[翻译]Json.NET API-Linq to Json Basic Operator(基本操作)2010-01-02 03:02 by chenkai, 268 visits, [url=file:///C:/Documents
and Settings/Administrator/Application
Data/Tencent/QQ/Misc/com.tencent.qzone/qzonepackage/blog/blank.htm#]网摘[/url], 收藏, 编辑
在Json.NET开源的组件的API文档中看到其中有个Linq To Json基本操作.详细看了其中API 中Linq to SQL命名空间下定义类方法.以及实现, 觉得参与Linq 来操作Json从某种程度上提高生成Json字符窜的效率, 特别对数据库中批量的数据. 但是也从侧面也增加程序员编码的难度(如果刚用不熟练情况下 主要是在编码中控制生成Json字符窜正确的格式),另外一个关键借助了Linq对Json数据操作和转换更加直接.Linq To SQL 空间目的使用户利用Linq更加直接创建和查询Json对象. 翻译文档如下:
A:Creating Json-(利用Linq快速创建Json Object)
Newtonsoft.Json.Linq 空间下有多个方法可以创建一个Json对象. 简单方法虽然能够创建,但是对编码而言较多略显累赘.简单创建代码如下:
1 JArray array = new JArray();
2 JValue text = new JValue("Manual text");
3 JValue date = new JValue(new DateTime(2000, 5, 23));
4
5 array.Add(text);
6 array.Add(date);
7
8 string json = array.ToString();
10 //生成的Json字符窜如下:
11 // [
12 // "Manual text",
13 // "\/Date(958996800000+1200)\/"
14 // ]


JArray是Newtonsoft.Json.Linq空间扩展的类表示一个Json数组.而JValue代表JSON值(字符串,整数,日期等) .
简单利用Linq To SQL创建一个Json Object:
Json.NET API-Linq to Json Basic Operator - 20:49 - 20:49代码 1 List<Post> posts = GetPosts();
2
3 JObject rss =
4 new JObject(
5 new JProperty("channel",
6 new JObject(
7 new JProperty("title", "James Newton-King"),
8 new JProperty("link", "http://james.newtonking.com"),
9 new JProperty("description", "James Newton-King's blog."),
10 new JProperty("item",
11 new JArray(
12 from p in posts
13 orderby p.Title
14 select new JObject(
15 new JProperty("title", p.Title),
16 new JProperty("description", p.Description),
17 new JProperty("link", p.Link),
18 new JProperty("category",
19 new JArray(
20 from c in p.Categories
21 select new JValue(c)))))))));
22
23 Console.WriteLine(rss.ToString());
24 //生成的Json字符窜如下:
25 //{
26 // "channel": {
27 // "title": "James Newton-King",
28 // "link": "http://james.newtonking.com",
29 // "description": "James Newton-King's blog.",
30 // "item": [
31 // {
32 // "title": "Json.NET 1.3 + New license + Now on CodePlex",
33 // "description": "Annoucing the release of Json.NET 1.3, the MIT license and the source being available on CodePlex",
34 // "link": "http://james.newtonking.com/projects/json-net.aspx",
35 // "category": [
36 // "Json.NET",
37 // "CodePlex"
38 // ]
39 // },
40 // {
41 // "title": "LINQ to JSON beta",
42 // "description": "Annoucing LINQ to JSON",
43 // "link": "http://james.newtonking.com/projects/json-net.aspx",
44 // "category": [
45 // "Json.NET",
46 // "LINQ"
47 // ]
48 // }
49 // ]
50 // }
51 //}
52

分析一下: 如果按照普通方法把一个List集合生成Json对象字符窜.步骤如下: List首先从数据库中取出.然后利用JsonConvert实体类下的SerializeObject()方法实例化才能返回Json字符窜. 相对而言Linq 直接操作数据库数据 一步到位 所以在编程效率上实现提高.
你可以FromObject()方法从一个非Json类型对象创建成Json Object.(自定义对象):
Json.NET API-Linq to Json Basic Operator - 20:49 - 20:49代码 1 JObject o = JObject.FromObject(new
2 {
3 channel = new
4 {
5 title = "James Newton-King",
6 link = "http://james.newtonking.com",
7 description = "James Newton-King's blog.",
8 item =
9 from p in posts
10 orderby p.Title
11 select new
12 {
13 title = p.Title,
14 description = p.Description,
15 link = p.Link,
16 category = p.Categories
17 }
18 }
19 });
20

最后可以通过Pares()方法把一个String字符窜创建一个Json对象:(手写控制Json格式):
1 string json = @"{
2 CPU: 'Intel',
3 Drives: [
4 'DVD read/writer',
5 ""500 gigabyte hard drive""
6 ]
7 }";
8
9 JObject o = JObject.Parse(json);
10

B:查询Json Object
当查询一个Json Object属性时最有用方法分别为:Children()方法和Property Index(属性索引),Children()方法将返回Json Object所有的Json子实体. 如果它是一个JObject将返回一个属性集合.如果是JArray返回一个数组值的集合. 但是Property Index用户获得特定的Children子实体.无论是JSON数组索引或JSON对象的属性名的位置.
Json.NET API-Linq to Json Basic Operator - 20:49 - 20:49代码 1 var postTitles =
2 from p in rss["channel"]["item"].Children()
3 select (string)p["title"];
4
5 foreach (var item in postTitles)
6 {
7 Console.WriteLine(item);
8 }
9
10 //LINQ to JSON beta
11 //Json.NET 1.3 + New license + Now on CodePlex
12
13 var categories =
14 from c in rss["channel"]["item"].Children()["category"].Values<string>()
15 group c by c into g
16 orderby g.Count() descending
17 select new { Category = g.Key, Count = g.Count() };
18
19 foreach (var c in categories)
20 {
21 Console.WriteLine(c.Category + " - Count: " + c.Count);
22 }
24 //Json.NET - Count: 2
25 //LINQ - Count: 1
26 //CodePlex - Count: 1


Linq to Json常常用于手动把一个Json Object转换成.NET对象 .
Json.NET API-Linq to Json Basic Operator - 20:49 - 20:49代码 1 public class Shortie
2 {
3 public string Original { get; set; }
4 public string Shortened { get; set; }
5 public string Short { get; set; }
6 public ShortieException Error { get; set; }
7 }
8
9 public class ShortieException
10 {
11 public int Code { get; set; }
12 public string ErrorMessage { get; set; }
13 }
14

手动之间的序列化和反序列化一个.NET对象是最常用情况是JSON Object 和需要的。NET对象不匹配情况下.
Json.NET API-Linq to Json Basic Operator - 20:49 - 20:49代码 1 string jsonText = @"{
2 ""short"":{
3 ""original"":""http://www.foo.com/"",
4 ""short"":""krehqk"",
5 ""error"":{
6 ""code"":0,
7 ""msg"":""No action taken""}
8 }";
9
10 JObject json = JObject.Parse(jsonText);
11
12 Shortie shortie = new Shortie
13 {
14 Original = (string)json["short"]["original"],
15 Short = (string)json["short"]["short"],
16 Error = new ShortieException
17 {
18 Code = (int)json["short"]["error"]["code"],
19 ErrorMessage = (string)json["short"]["error"]["msg"]
20 }
21 };
22
23 Console.WriteLine(shortie.Original);
24 // http://www.foo.com/
25
26 Console.WriteLine(shortie.Error.ErrorMessage);
27 // No action taken
28

个人翻译不是很好,最近主要是用的比较频繁. 今天总结一些基本用法.如想看原版的Linq To Json 编译 请参考官方地址下API,代码如果看不懂可以查看Newtonsoft.Json.Linq命名空间下定义类和集成静待方法或直接联系我.

原文地址:https://www.cnblogs.com/WangJinYang/p/2679762.html