C#關於JArray和JObject封裝JSON物件

風靈使發表於2018-10-18

1、JObject:基本的json物件

    /// <summary>
    /// Gets the j object.
    /// </summary>
    /// <returns></returns>
    public JObject GetJObject()
    {
        var obj = new JObject {{"Name", "Mark" } };
        return obj;
    }

在這裡插入圖片描述

2、JObject:巢狀子物件(JObjectJObject

    /// <summary>
    /// Gets the j object.
    /// </summary>
    /// <returns></returns>
    public JObject GetJObject()
    {
        var obj = new JObject {{"Name", "Mark"}, {"Age", 8 }};
        var info = new JObject {{"Phone", "132****7777"}, {"Gender", "男"}};
        obj.Add("Info", info);
        return obj;
    }

在這裡插入圖片描述

3、JArray:基本json物件中的陣列

    /// <summary>
    /// Gets the j array.
    /// </summary>
    /// <returns></returns>
    public JArray GetJArray()
    {
        var jarray = new JArray();
        var mark = new JObject { { "Name", "Mark" }, { "Age", 8 } };
        var jack = new JObject { { "Name", "Jack" }, { "Age", 9 } };
        jarray.Add(mark);
        jarray.Add(jack);
        return jarray;
    }

在這裡插入圖片描述

4、JArray: 多個json物件陣列

    /// <summary>
    /// Gets the j array.
    /// </summary>
    /// <returns></returns>
    public JObject GetJArray()
    {
        var obj = new JObject();
        var student = new JArray
        {
            new JObject {{ "Name", "Mark" }, { "Age", 8 } },
            new JObject {{ "Name", "Jack" }, { "Age", 9 } }
        };
        var results = new JArray
        {
            new JObject {{ "Subject", "語文"}, { "Score", 100}},
            new JObject {{ "Subject", "數學" }, { "Score", 88}}
        };
        obj.Add("Student", student);
        obj.Add("Results", results);
        return obj;
    }

在這裡插入圖片描述

5、JArray:json陣列巢狀陣列(一個學生對應多個課程分數)

    /// <summary>
    /// Gets the results.
    /// </summary>
    /// <returns></returns>
    public JObject GetResults()
    {
        var mark = new JObject { { "Name", "Mark" }, { "Age", "8" } };
        var results = new JArray
        {
            new JObject {{ "Subject", "語文"}, { "Score", 100}},
            new JObject {{ "Subject", "數學" }, { "Score", 88}}
        };            
        mark.Add("Results", results);
        return mark;
    }

在這裡插入圖片描述

//--------------------------------------------------------------------------

Json.Net系列教程 4.Linq To JSON

一.Linq to JSON是用來幹什麼的?

Linq to JSON是用來操作JSON物件的.可以用於快速查詢,修改和建立JSON物件.當JSON物件內容比較複雜,而我們僅僅需要其中的一小部分資料時,可以考慮使用Linq to JSON來讀取和修改部分的資料而非反序列化全部.

二.建立JSON陣列和物件

在進行Linq to JSON之前,首先要了解一下用於操作Linq to JSON的類.

類名 說明
JObject 用於操作JSON物件
JArray 用語操作JSON陣列
JValue 表示陣列中的值
JProperty 表示物件中的屬性,以"key/value"形式
JToken 用於存放Linq to JSON查詢後的結果

1.建立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());

結果:
在這裡插入圖片描述

除此之外,還可以通過一下方式來獲取JObject.JArray類似。

方法 說明
JObject.Parse(string json) json含有JSON物件的字串,返回為JObject物件
JObject.FromObject(object o) o為要轉化的物件,返回一個JObject物件
JObject.Load(JsonReader reader) reader包含著JSON物件的內容,返回一個JObject物件

2.建立JSON陣列

            JArray arr = new JArray();
            arr.Add(new JValue(1));
            arr.Add(new JValue(2));
            arr.Add(new JValue(3));
            Console.WriteLine(arr.ToString());

結果:
在這裡插入圖片描述

三.使用Linq to JSON

1.查詢
首先準備json字串,是一個包含員工基本資訊的json

string json = "{\"Name\" : \"Jack\", \"Age\" : 34, \"Colleagues\" : [{\"Name\" : \"Tom\" , \"Age\":44},{\"Name\" : \"Abel\",\"Age\":29}] }";

①獲取該員工的姓名

           //將json轉換為JObject
            JObject jObj = JObject.Parse(json);
            //通過屬性名或者索引來訪問,僅僅是自己的屬性名,而不是所有的
            JToken ageToken =  jObj["Age"];
            Console.WriteLine(ageToken.ToString());

結果:

②獲取該員工同事的所有姓名

            //將json轉換為JObject
            JObject jObj = JObject.Parse(json);
            var names=from staff in jObj["Colleagues"].Children()
                             select (string)staff["Name"];
            foreach (var name in names)
                Console.WriteLine(name);

"Children()"可以返回所有陣列中的物件

結果:

2.修改

①現在我們發現獲取的json字串中Jack的年齡應該為35

            //將json轉換為JObject
            JObject jObj = JObject.Parse(json);
            jObj["Age"] = 35;
            Console.WriteLine(jObj.ToString());

結果:

注意不要通過以下方式來修改:

            JObject jObj = JObject.Parse(json);
            JToken age = jObj["Age"];
            age = 35;

②現在我們發現Jack的同事Tom的年齡錯了,應該為45

            //將json轉換為JObject
            JObject jObj = JObject.Parse(json);
            JToken colleagues = jObj["Colleagues"];
            colleagues[0]["Age"] = 45;
            jObj["Colleagues"] = colleagues;//修改後,再賦給物件
            Console.WriteLine(jObj.ToString());

結果:
3.刪除
①現在我們想刪除Jack的同事

            JObject jObj = JObject.Parse(json);
            jObj.Remove("Colleagues");//跟的是屬性名稱
            Console.WriteLine(jObj.ToString());

結果:
②現在我們發現Abel不是Jack的同事,要求從中刪除

            JObject jObj = JObject.Parse(json);
            jObj["Colleagues"][1].Remove();
            Console.WriteLine(jObj.ToString());

結果:

4.新增
①我們發現Jack的資訊中少了部門資訊,要求我們必須新增在Age的後面

            //將json轉換為JObject
            JObject jObj = JObject.Parse(json);
            jObj["Age"].Parent.AddAfterSelf(new JProperty("Department", "Personnel Department"));
            Console.WriteLine(jObj.ToString());

結果:

②現在我們又發現,Jack公司來了一個新同事Linda

            //將json轉換為JObject
            JObject jObj = JObject.Parse(json);
            JObject linda = new JObject(new JProperty("Name", "Linda"), new JProperty("Age", "23"));
            jObj["Colleagues"].Last.AddAfterSelf(linda);
            Console.WriteLine(jObj.ToString());

結果:

四.簡化查詢語句

使用函式SelectToken可以簡化查詢語句,具體:
①利用SelectToken來查詢名稱

            JObject jObj = JObject.Parse(json);
            JToken name = jObj.SelectToken("Name");
            Console.WriteLine(name.ToString());

結果:

②利用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());

結果:

③查詢最後一名同事的年齡

            //將json轉換為JObject
            JObject jObj = JObject.Parse(json);
            var age = jObj.SelectToken("Colleagues[1].Age");
            Console.WriteLine(age.ToString());

結果:

FAQ

1.如果Json中的Key是變化的但是結構不變,如何獲取所要的內容?

例如:

{
"trends":
{
"2013-05-31 14:31":
[
{"name":"我不是誰的偶像",
"query":"我不是誰的偶像",
"amount":"65172",
"delta":"1596"},
{"name":"世界無煙日","query":"世界無煙日","amount":"33548","delta":"1105"},
{"name":"最萌身高差","query":"最萌身高差","amount":"32089","delta":"1069"},
{"name":"中國合夥人","query":"中國合夥人","amount":"25634","delta":"2"},
{"name":"exo迴歸","query":"exo迴歸","amount":"23275","delta":"321"},
{"name":"新一吻定情","query":"新一吻定情","amount":"21506","delta":"283"},
{"name":"進擊的巨人","query":"進擊的巨人","amount":"20358","delta":"46"},
{"name":"誰的青春沒缺失","query":"誰的青春沒缺失","amount":"17441","delta":"581"},
{"name":"我愛幸運七","query":"我愛幸運七","amount":"15051","delta":"255"},
{"name":"母愛10平方","query":"母愛10平方","amount":"14027","delta":"453"}
]
},
"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<Trend>(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; }
}

相關文章