首頁 > 軟體

C#中的Linq to JSON操作詳解

2022-06-01 22:01:03

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的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com