C#生成JSON使用Newtonsoft.Json 最新方法

1、JObject:基本的json对象

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

2、JObject:嵌套子对象(JObject嵌JObject)

    /// 
    /// Gets the j object.
    /// 
    /// 
    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对象中的数组

    /// 
    /// Gets the j array.
    /// 
    /// 
    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对象数组

    /// 
    /// Gets the j array.
    /// 
    /// 
    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数组嵌套数组(一个学生对应多个课程分数)

    /// 
    /// Gets the results.
    /// 
    /// 
    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;
    }
可以参考这两篇文章http://blog.csdn.net/zxq1138634642/article/details/9044197


http://www.cnblogs.com/mcgrady/archive/2013/06/08/3127781.html


你可能感兴趣的:(C#生成JSON使用Newtonsoft.Json 最新方法)