语言吧技术网欢迎您投稿,程序员的世界我懂你!=====>点此登录投搞
当前位置: 首页 >>ASP.NET >>C#基础 >>C# 关于JArray和JObject封装JSON对象

C# 关于JArray和JObject封装JSON对象

2019/11/12 9:30:42 0人评论 131次 作者:乌匠

C# 关于JArray和JObject封装JSON对象及使用方法…

直入主题,不废话...

1、JObject:基本的json对象

    /// <summary>

    /// Gets the j object.

    /// </summary>

    /// <returns></returns>

    public JObject GetJObject()

    {

        var obj = new JObject {{"Name", "Mark" } };

        return obj;

    }

1.jpg

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;

    }

2.jpg

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;

    }

3.jpg

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;

    }

4.jpg

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.jpg

总结:写接口的时候,类似上面的5种情况经常会遇到,有时候会弄糊涂,算一次简单的复习吧


CopyRight:2007-2018 语言吧 备案ICP:湘ICP备09009000号-15 http://www.yuyanba.com
欢迎【康乃狄克州 】的朋友
内容与素材部分来源于网络,如有侵权请告知删除
分享按钮