C#中的Linq to JSON操作詳解
Linq to JSON是用來操作JSON對象的,可以用於快速查詢、修改和創建JSON對象。
當JSON對象內容比較復雜,而我們僅僅需要其中的一小部分數據時,可以考慮使用Linq to JSON來讀取和修改部分的數據而非反序列化全部。
參考:Json.NET Documentation
在進行Linq to JSON之前,首先要瞭解一下用於操作Linq to JSON的類.
類名 | 說明 |
---|---|
JObject | 用於操作JSON對象 |
JArray | 用語操作JSON數組 |
JValue | 表示數組中的值 |
JProperty | 表示對象中的屬性,以"key/value"形式 |
JToken | 用於存放Linq to JSON查詢後的結果 |
一、創建JObject and JArrary實例
1、手動創建JSON
設置值和一次創建一個對象或數組可以讓您完全控制,但是它比其他選項更冗長。
1、創建JSON對象,JObject
JObject staff = new JObject(); staff.Add(new JProperty("Name", "Jack")); staff.Add(new JProperty("Age", 33)); staff.Add(new JProperty("Department", "Personnel Department")); staff.Add(new JProperty("Leader", new JObject(new JProperty("Name", "Tom"), new JProperty("Age", 44), new JProperty("Department", "Personnel Department")))); Console.WriteLine(staff.ToString()); //返回 //{ // "Name": "Jack", // "Age": 33, // "Department": "Personnel Department", // "Leader": { // "Name": "Tom", // "Age": 44, // "Department": "Personnel Department" // } //}
2、創建JSON數組,JArrary
JArray arr = new JArray(); arr.Add(new JValue(1)); arr.Add(new JValue(2)); arr.Add(new JValue(3)); Console.WriteLine(arr.ToString()); //返回 //[ // 1, // 2, // 3 //]
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、從對象創建JSON
JObject.FromObject(object o):o為要轉化的對象,返回一個JObject對象
最後一個選項是使用FromObject()方法從非JSON類型創建JSON對象。
下面的示例展示瞭如何從匿名對象創建JSON對象,但是任何. net類型都可以與FromObject一起創建JSON。
var posts = new[] { new { 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", Categories=new[]{ "Json.NET","CodePlex"} }, new { Title="LINQ to JSON beta", Description= "Announcing LINQ to JSON", Link="http://james.newtonking.com/projects/json-net.aspx", Categories=new[]{ "Json.NET","LINQ"} }, }; 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 } } }); Console.WriteLine(o.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" // ] // } // ] // } //}
4、解析JSON文本
JObject.Parse(string json):json含有JSON對象的字符串,返回為JObject對象
//解析JSON對象 string json = @"{ CPU: 'Intel', Drives: [ 'DVD read/writer', '500 gigabyte hard drive' ] }"; JObject o = JObject.Parse(json); //解析JSON數組 string json = @"[ 'Small', 'Medium', 'Large' ]"; JArray a = JArray.Parse(json);
5、從文件中加載JSON
using (StreamReader reader = File.OpenText(@"c:\person.json")) { JObject o = (JObject)JToken.ReadFrom(new JsonTextReader(reader)); // do stuff }
二、使用JsonConvert.DeserializeObject反序列化JOSN片段
1、數組數據
string jsonArrayText= "[{'a','al'.'b','b1'},{'a','a2'.'b','b2'}]"; JArray ja = (JArray)JsonConvert.DeserializeObject(jsonArrayText); string ja1a==ja[1]["a"].ToString(); //或者 JObject o=(JObject)ja[1]; string ja1a=o["a"].ToString();
2、對象格式
siring jsonText= "{\"beijing\":{\"zone\":\"海淀\",\"zone_en\":\"haidian\"}"; JObject jo =(JObject)JsonConvert.DeserializeObject(jsonArrayText); string zone =jo["beijing"]["zone"].ToString();
三、修改JObject and JArrary實例
string json = @"{ 'post':{ 'Title':'修改JArray和JObject', 'Link':'http://write.blog.csdn.net', 'Description':'這是一個修改JArray和JObject的演示案例', 'Item':[] } }"; JObject o = JObject.Parse(json); JObject post = (JObject)o["post"]; post["Title"] = ((string)post["Title"]).ToUpper(); post["Link"] = ((string)post["Link"]).ToUpper(); post.Property("Description").Remove(); post.Property("Link").AddAfterSelf(new JProperty("New", "新添加的屬性")); JArray a = (JArray)post["Item"]; a.Add("修改JArray"); a.Add("修改JObject");
移除屬性
JObject jObj = JObject.Parse(json); jObj.Remove("Colleagues");//跟的是屬性名稱 Console.WriteLine(jObj.ToString());
四、查詢JObject and JArrary實例
將一個值從LINQ轉換為JSON的最簡單方法是:使用JObject/JArray上的ItemObject索引,然後將返回的JValue轉換為所需的類型。
string json = @"{ '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 the source on CodePlex', 'link': 'http://james.newtonking.com/projects/json-net.aspx', 'categories': [ 'Json.NET', 'CodePlex' ] }, { 'title': 'LINQ to JSON beta', 'description': 'Announcing LINQ to JSON', 'link': 'http://james.newtonking.com/projects/json-net.aspx', 'categories': [ 'Json.NET', 'LINQ' ] } ] } }"; JObject rss = JObject.Parse(json); string rssTitle = (string)rss["channel"]["title"]; // James Newton-King string itemTitle = (string)rss["channel"]["item"][0]["title"]; // Json.NET 1.3 + New license + Now on CodePlex JArray categories = (JArray)rss["channel"]["item"][0]["categories"]; // ["Json.NET", "CodePlex"] IList<string> categoriesText = categories.Select(c => (string)c).ToList(); // Json.NET // CodePlex
判斷Key是否存在
JToken test = new JObject(); if (test["a"] == null) { Console.WriteLine("鍵值key不存在!"); } JObject test1 = test as JObject; if (test1.Property("a") == null || test1.Property("a").ToString() == "") { Console.WriteLine("鍵值key不存在!"); }
五、用LINQ表達式進行查詢
也可以使用LINQ查詢JObject/JArray。
Children()以IEnumerable的形式返回JObject/JArray的子值,然後可以使用標準的Where/OrderBy/Select LINQ操作符查詢這些子值。
註意:
Children()返回token的所有子元素。如果它是一個JObject,它將返回一個要使用的屬性集合,如果它是一個JArray,您將得到一個數組值的集合。
var postTitles = from p in rss["channel"]["item"] select (string)p["title"]; foreach (var item in postTitles) { Console.WriteLine(item); } //LINQ to JSON beta //Json.NET 1.3 + New license + Now on CodePlex var categories = from c in rss["channel"]["item"].SelectMany(i => i["categories"]).Values<string>() group c by c into g orderby g.Count() descending select new { Category = g.Key, Count = g.Count() }; foreach (var c in categories) { Console.WriteLine(c.Category + " - Count: " + c.Count); } //Json.NET - Count: 2 //LINQ - Count: 1 //CodePlex - Count: 1
可以使用LINQ to JSON手動將JSON轉換為. net對象。
當您處理與. net對象不匹配的JSON時,手動序列化和反序列化. net對象是很有用的。
string jsonText = @"{ 'short': { 'original': 'http://www.foo.com/', 'short': 'krehqk', 'error': { 'code': 0, 'msg': 'No action taken' } } }"; JObject json = JObject.Parse(jsonText); Shortie shortie = new Shortie { Original = (string)json["short"]["original"], Short = (string)json["short"]["short"], Error = new ShortieException { Code = (int)json["short"]["error"]["code"], ErrorMessage = (string)json["short"]["error"]["msg"] } }; Console.WriteLine(shortie.Original); // http://www.foo.com/ Console.WriteLine(shortie.Error.ErrorMessage); // No action taken public class Shortie { public string Original { get; set; } public string Shortened { get; set; } public string Short { get; set; } public ShortieException Error { get; set; } } public class ShortieException { public int Code { get; set; } public string ErrorMessage { get; set; } }
六、使用函數SelectToken生成JToken對象可以簡化查詢語句
1、SelectToken
SelectToken是JToken上的一個方法,它將字符串路徑作為子Token名,返回子Token。如果在路徑的位置找不到Token,則SelectToken返回空引用。
該路徑由屬性名和按句點分隔的數組索引組成,例如manufacturer [0]. name。
JObject jObj = JObject.Parse(json); JToken name = jObj.SelectToken("Name"); Console.WriteLine(name.ToString());
結果:Jack
2、使用LINQ來SelectToken
SelectToken支持JSONPath查詢。點擊這裡瞭解更多關於JSONPath的信息。
查詢最後一名同事的年齡
//將json轉換為JObject JObject jObj = JObject.Parse(json); var age = jObj.SelectToken("Colleagues[1].Age"); Console.WriteLine(age.ToString()); // manufacturer with the name 'Acme Co' JToken acme = o.SelectToken("$.Manufacturers[?(@.Name == 'Acme Co')]"); Console.WriteLine(acme); // { "Name": "Acme Co", Products: [{ "Name": "Anvil", "Price": 50 }] } // name of all products priced 50 and above IEnumerable pricyProducts = o.SelectTokens("$..Products[?(@.Price >= 50)].Name"); foreach (JToken item in pricyProducts) { Console.WriteLine(item); } // Anvil // Elbow Grease
結果:29
3、使用JSONPath來SelectToken
SelectToken可以與標準的LINQ方法結合使用。
利用SelectToken來查詢所有同事的名字
JObject jObj = JObject.Parse(json); var names = jObj.SelectToken("Colleagues").Select(p => p["Name"]).ToList(); foreach (var name in names) Console.WriteLine(name.ToString()); IList<string> storeNames = o.SelectToken("Stores").Select(s => (string)s).ToList(); // Lambton Quay // Willis Street IList<string> firstProductNames = o["Manufacturers"].Select(m => (string)m.SelectToken("Products[1].Name")).ToList(); // null // Headlight Fluid decimal totalPrice = o["Manufacturers"].Sum(m => (decimal)m.SelectToken("Products[0].Price"));
結果:Tom Abel
七、如果Json中的Key是變化的但是結構不變,如何獲取所要的內容?
例如:
{ "trends": { "2013-05-31 14:31": [ { "name": "我不是誰的偶像", "query": "我不是誰的偶像", "amount": "65172", "delta": "1596" }, { "name": "世界無煙日", "query": "世界無煙日", "amount": "33548", "delta": "1105" } ] }, "as_of": 1369981898 }
其中的"2013-05-31 14:31"是變化的key,如何獲取其中的"name","query","amount","delta"等信息呢?
通過Linq可以很簡單地做到:
var jObj = JObject.Parse(jsonString); var tends = from c in jObj.First.First.First.First.Children() select JsonConvert.DeserializeObject(c.ToString()); public class Trend { public string Name { get; set; } public string Query { get; set; } public string Amount { get; set; } public string Delta { get; set; } }
八、綜合實例
void Main() { string json = "{\"Name\" : \"Jack\", \"Age\" : 34, \"Colleagues\" : [{\"Name\" : \"Tom\" , \"Age\":44},{\"Name\" : \"Abel\",\"Age\":29}] }"; // 獲取員工名稱 JObject jObject = JObject.Parse(json); var name = jObject.Value<string>("Name"); Console.WriteLine(name); // 獲取員工年齡 JToken jToken = jObject.SelectToken("Age"); Console.WriteLine(jToken.ToString()); // 獲取同事信息 JToken jToken1 = jObject["Colleagues"]; Console.WriteLine(jToken1.ToString()); Console.WriteLine("============================="); // 獲取員工同事的所有姓名 var names = from staff in jToken1.Children() select (string)staff["Name"]; // var names = jObject.SelectToken("Colleagues").Select(p => p["Name"]).ToList(); foreach (var item in names) { Console.WriteLine(item); } Console.WriteLine("============================="); // 修改Jack的年齡 jObject["Age"] = 99; Console.WriteLine(jObject.ToString()); // 修改同事Tome的年齡 jToken1[0]["Age"] = 45; Console.WriteLine(jObject.ToString()); Console.WriteLine("============================="); // Abel離職瞭 jObject["Colleagues"][1].Remove(); Console.WriteLine(jObject.ToString()); // 移除Jack的同事 jObject.Remove("Colleagues"); Console.WriteLine(jObject.ToString()); Console.WriteLine("============================="); // Jack缺少部門信息 jObject["Age"].Parent.AddAfterSelf(new JProperty("Department", "總裁辦")); // 來瞭一個新員工Jerry JObject linda = new JObject(new JProperty("Name", "Linda"), new JProperty("Age", "23")); jObject.Add(new JProperty("Colleagues", new JArray() { linda })); Console.WriteLine(jObject.ToString()); } // Define other methods and classes here
到此這篇關於C#使用LINQ to JSON的文章就介紹到這瞭。希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。
推薦閱讀:
- c#添加Newtonsoft.Json包的操作
- C#使用Newtonsoft.Json中的JObject對象
- c# Newtonsoft.Json 常用方法總結
- 解析C#拼接Json串的幾種方法
- c#解析jobject的數據結構