天天看點

[翻譯]Json.NET API-Linq to Json Basic Operator(基本操作)

在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)

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 // ] 

簡單利用Linq To SQL建立一個Json Object:

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 //}

分析一下: 如果按照普通方法把一個List集合生成Json對象字元竄.步驟如下: List首先從資料庫中取出.然後利用JsonConvert實體類下的SerializeObject()方法執行個體化才能傳回Json字元竄. 相對而言Linq 直接操作資料庫資料 一步到位 是以在程式設計效率上實作提高.

你可以FromObject()方法從一個非Json類型對象建立成Json Object.(自定義對象):

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 });

最後可以通過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); 

B:查詢Json Object

當查詢一個Json Object屬性時最有用方法分别為:Children()方法和Property Index(屬性索引),Children()方法将傳回Json Object所有的Json子實體. 如果它是一個JObject将傳回一個屬性集合.如果是JArray傳回一個數組值的集合. 但是Property Index使用者獲得特定的Children子實體.無論是JSON數組索引或JSON對象的屬性名的位置.

1 var postTitles =

 2   from p in rss["channel"]["item"].Children()

 3   select (string)p["title"];

 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對象 .

1 public class Shortie

 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 }

 9 public class ShortieException

10 {

11   public int Code { get; set; }

12   public string ErrorMessage { get; set; }

13 }

手動之間的序列化和反序列化一個.NET對象是最常用情況是JSON Object 和需要的。NET對象不比對情況下.

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 }";

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                   };

23 Console.WriteLine(shortie.Original);

24 // http://www.foo.com/

25  

26 Console.WriteLine(shortie.Error.ErrorMessage);

27 // No action taken

本文轉自chenkaiunion 51CTO部落格,原文連結:http://blog.51cto.com/chenkai/765198