首頁 > 軟體

C#使用JArray和JObject封裝JSON物件

2022-07-23 14:03:21

1、JObject:基本的json物件

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

2、JObject:巢狀子物件(JObject嵌JObject)

	/// <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;
    }

總結:寫介面的時候,類似上面的5種情況經常會遇到,有時候會弄糊塗,算一次簡單的複習吧。

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對it145.com的支援。如果你想了解更多相關內容請檢視下面相關連結


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