C#中的Linq?to?JSON操作詳解
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é)果 |
一、創(chuàng)建JObject and JArrary實(shí)例
1、手動創(chuàng)建JSON
設(shè)置值和一次創(chuàng)建一個對象或數(shù)組可以讓您完全控制,但是它比其他選項(xiàng)更冗長。
1、創(chuàng)建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、創(chuàng)建JSON數(shù)組,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創(chuàng)建JSON
使用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"
// ]
// }
// ]
// }
//}3、從對象創(chuàng)建JSON
JObject.FromObject(object o):o為要轉(zhuǎn)化的對象,返回一個JObject對象
最后一個選項(xiàng)是使用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"
// ]
// }
// ]
// }
//}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數(shù)組
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、數(shù)組數(shù)據(jù)
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實(shí)例
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實(shí)例
將一個值從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判斷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表達(dá)式進(jìn)行查詢
也可以使用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可以使用LINQ to JSON手動將JSON轉(zhuǎn)換為. net對象。
當(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; }
}六、使用函數(shù)SelectToken生成JToken對象可以簡化查詢語句
1、SelectToken
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
2、使用LINQ來SelectToken
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
3、使用JSONPath來SelectToken
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
七、如果Json中的Key是變化的但是結(jié)構(gòu)不變,如何獲取所要的內(nèi)容?
例如:
{
"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; }
}八、綜合實(shí)例
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到此這篇關(guān)于C#使用LINQ to JSON的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C# 運(yùn)用params修飾符來實(shí)現(xiàn)變長參數(shù)傳遞的方法
一般來說,參數(shù)個數(shù)都是固定的,定義為集群類型的參數(shù)可以實(shí)現(xiàn)可變數(shù)目參數(shù)的目的,但是.NET提供了更靈活的機(jī)制來實(shí)現(xiàn)可變數(shù)目參數(shù),這就是使用params修飾符2013-09-09
Winform學(xué)生信息管理系統(tǒng)登陸窗體設(shè)計(1)
這篇文章主要為大家詳細(xì)介紹了Winform學(xué)生信息管理系統(tǒng)登陸窗體設(shè)計思路,感興趣的小伙伴們可以參考一下2016-05-05
WPF+SkiaSharp實(shí)現(xiàn)自繪彈幕效果
這篇文章主要為大家詳細(xì)介紹了如何利用WPF和SkiaSharp實(shí)現(xiàn)自制彈幕效果,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)或工作有一定幫助,感興趣的小伙伴可以了解一下2022-09-09
C#設(shè)計模式之Builder生成器模式解決帶老婆配置電腦問題實(shí)例
這篇文章主要介紹了C#設(shè)計模式之Builder生成器模式解決帶老婆配置電腦問題,簡單介紹了生成器模式的概念、功能并結(jié)合具體實(shí)例形式分析了C#生成器模式解決配電腦問題的步驟與相關(guān)操作技巧,需要的朋友可以參考下2017-09-09
C#使用WebClient登錄網(wǎng)站并抓取登錄后的網(wǎng)頁信息實(shí)現(xiàn)方法
這篇文章主要介紹了C#使用WebClient登錄網(wǎng)站并抓取登錄后的網(wǎng)頁信息實(shí)現(xiàn)方法,涉及C#基于會話操作登陸網(wǎng)頁及頁面讀取相關(guān)操作技巧,需要的朋友可以參考下2017-05-05

