您好,登錄后才能下訂單哦!
今天小編給大家分享一下C#中的Linq to JSON操作實(shí)例分析的相關(guān)知識點(diǎn),內(nèi)容詳細(xì),邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。
Linq to JSON是用來操作JSON對象的,可以用于快速查詢、修改和創(chuàng)建JSON對象。
當(dāng)JSON對象內(nèi)容比較復(fù)雜,而我們僅僅需要其中的一小部分?jǐn)?shù)據(jù)時,可以考慮使用Linq to JSON來讀取和修改部分的數(shù)據(jù)而非反序列化全部。
在進(jìn)行Linq to JSON之前,首先要了解一下用于操作Linq to JSON的類.
類名 | 說明 |
---|---|
JObject | 用于操作JSON對象 |
JArray | 用語操作JSON數(shù)組 |
JValue | 表示數(shù)組中的值 |
JProperty | 表示對象中的屬性,以"key/value"形式 |
JToken | 用于存放Linq to JSON查詢后的結(jié)果 |
設(shè)置值和一次創(chuàng)建一個對象或數(shù)組可以讓您完全控制,但是它比其他選項更冗長。
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" // } //}
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 //]
使用LINQ聲明式地創(chuàng)建JSON對象,是一種從值集合創(chuàng)建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" // ] // } // ] // } //}
JObject.FromObject(object o):o為要轉(zhuǎn)化的對象,返回一個JObject對象
最后一個選項是使用FromObject()方法從非JSON類型創(chuàng)建JSON對象。
下面的示例展示了如何從匿名對象創(chuàng)建JSON對象,但是任何. net類型都可以與FromObject一起創(chuàng)建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 = //返回數(shù)組 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" // ] // } // ] // } //}
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數(shù)組 string json = @"[ 'Small', 'Medium', 'Large' ]"; JArray a = JArray.Parse(json);
using (StreamReader reader = File.OpenText(@"c:\person.json")) { JObject o = (JObject)JToken.ReadFrom(new JsonTextReader(reader)); // do stuff }
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();
siring jsonText= "{\"beijing\":{\"zone\":\"海淀\",\"zone_en\":\"haidian\"}"; JObject jo =(JObject)JsonConvert.DeserializeObject(jsonArrayText); string zone =jo["beijing"]["zone"].ToString();
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());
將一個值從LINQ轉(zhuǎn)換為JSON的最簡單方法是:使用JObject/JArray上的ItemObject索引,然后將返回的JValue轉(zhuǎn)換為所需的類型。
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
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查詢JObject/JArray。
Children()以IEnumerable的形式返回JObject/JArray的子值,然后可以使用標(biāo)準(zhǔn)的Where/OrderBy/Select LINQ操作符查詢這些子值。
注意:
Children()返回token的所有子元素。如果它是一個JObject,它將返回一個要使用的屬性集合,如果它是一個JArray,您將得到一個數(shù)組值的集合。
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
當(dāng)您處理與. 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上的一個方法,它將字符串路徑作為子Token名,返回子Token。如果在路徑的位置找不到Token,則SelectToken返回空引用。
該路徑由屬性名和按句點(diǎn)分隔的數(shù)組索引組成,例如manufacturer [0]. name。
JObject jObj = JObject.Parse(json); JToken name = jObj.SelectToken("Name"); Console.WriteLine(name.ToString());
結(jié)果:Jack
SelectToken支持JSONPath查詢。點(diǎn)擊這里了解更多關(guān)于JSONPath的信息。
查詢最后一名同事的年齡
//將json轉(zhuǎn)換為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
結(jié)果:29
SelectToken可以與標(biāo)準(zhǔn)的LINQ方法結(jié)合使用。
利用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"));
結(jié)果:Tom Abel
例如:
{ "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操作實(shí)例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會為大家更新不同的知識,如果還想學(xué)習(xí)更多的知識,請關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。