您好,登錄后才能下訂單哦!
今天小編給大家分享一下C#中的Linq to JSON操作實例分析的相關知識點,內容詳細,邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。
Linq to JSON是用來操作JSON對象的,可以用于快速查詢、修改和創建JSON對象。
當JSON對象內容比較復雜,而我們僅僅需要其中的一小部分數據時,可以考慮使用Linq to JSON來讀取和修改部分的數據而非反序列化全部。
在進行Linq to JSON之前,首先要了解一下用于操作Linq to JSON的類.
類名 | 說明 |
---|---|
JObject | 用于操作JSON對象 |
JArray | 用語操作JSON數組 |
JValue | 表示數組中的值 |
JProperty | 表示對象中的屬性,以"key/value"形式 |
JToken | 用于存放Linq to JSON查詢后的結果 |
設置值和一次創建一個對象或數組可以讓您完全控制,但是它比其他選項更冗長。
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聲明式地創建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" // ] // } // ] // } //}
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" // ] // } // ] // } //}
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);
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轉換為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
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的子值,然后可以使用標準的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
當您處理與. 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返回空引用。
該路徑由屬性名和按句點分隔的數組索引組成,例如manufacturer [0]. name。
JObject jObj = JObject.Parse(json); JToken name = jObj.SelectToken("Name"); Console.WriteLine(name.ToString());
結果:Jack
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
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
例如:
{ "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操作實例分析”這篇文章的所有內容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會為大家更新不同的知識,如果還想學習更多的知識,請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。