如何在C#MVC中生成正确的JSON结果

时间:2015-10-02 07:11:31

标签: c# json asp.net-mvc asp.net-mvc-4 c#-4.0

我正在使用C#开发MVC应用程序,并希望生成JSON结果,如:

var json = {
    id: "1",
    name: "Ram | 1",
    data: {},
    children: [{
        id: "2",
        name: "Hari | 2",
        data: {},
        children: [{
            id: "Sam3",
            name: "2.4",
            data: {},
            children: []
        }, {
            id: "4",
            name: "Jon | 4",
            data: {},
            children: [{
                id: "5",
                name: "Smith | 5",
                data: {},
                children: [{
                    id: "6",
                    name: "Max | 6",
                    data: {},
                    children: []
                }]
            }]
        }]
    }, {
        id: "7",
        name: "Himanshu | 7",
        data: {},
        children: [{
            id: "8",
            name: "Jack | 8",
            data: {},
            children: [{
                id: "9",
                name: "Mad | 9",
                data: {},
                children: [{
                    id: "10",
                    name: "Jacky | 10",
                    data: {},
                    children: []
                }, {
                    id: "11",
                    name: "Anchor | 11",
                    data: {},
                    children: []
                }]
            }, {
                id: "12",
                name: "Dam | 12",
                data: {},
                children: [{
                    id: "13",
                    name: "Xyz | 13",
                    data: {},
                    children: []
                }]
            }, {
                id: "14",
                name: "History | 14",
                data: {},
                children: [{
                    id: "15",
                    name: "java | 15",
                    data: {},
                    children: []
                }, {
                    id: "16",
                    name: "Blue | 16",
                    data: {},
                    children: []
                }, {
                    id: "17",
                    name: "Kali | 17",
                    data: {},
                    children: []
                }, {
                    id: "18",
                    name: "lon | 18",
                    data: {},
                    children: []
                }]
            }]
        }]
    }]
};`

我在C#中的JSON函数:

[HttpPost]
    public JsonResult CalculateTreeView(int sid)
    {
        /*
            Some Code Logic
        */
        if (res != null)
            if (res.l_id != 0)
                return Json(new { id = res.id, name = res.name + " | " + res.id, data = new { }, children = new object[] { CalculateTreeView(res.l_id) } });
            else
                return Json(new { id = res.id, name = res.name + " | " + res.id, data = new { }, children = new object[] { } });
        else
            return Json(new { id = res.id, name = res.name + " | " + res.id, data = new { }, children = new object[] { } });
    }

我的这个C#函数返回奇怪的输出我不知道为什么..

{
"id":1,
"name":"anant | 1",
"data":{},
"children":[{
        "ContentEncoding":null,
        "ContentType":null,
        "Data":{
            "id":2,
            "name":"Samir | 2",
            "data":{},
            "children":[{
                    "ContentEncoding":null,
                    "ContentType":null,
                    "Data":{
                        "id":4,
                        "name":"fjyfyj | 4",
                        "data":{},
                        "children":[{
                                "ContentEncoding":null,
                                "ContentType":null,
                                "Data":{
                                    "id":8,
                                    "name":"cdasdasd | 8",
                                    "data":{},
                                    "children":[]
                                    },
                                "JsonRequestBehavior":1,
                                "MaxJsonLength":null,
                                "RecursionLimit":null
                                }]
                            },
                        "JsonRequestBehavior":1,
                        "MaxJsonLength":null,
                        "RecursionLimit":null
                        }]
                    },
                    "JsonRequestBehavior":1,
                    "MaxJsonLength":null,
                    "RecursionLimit":null
            }]
        }

请帮我告诉我如何生成正确的JSON格式。

4 个答案:

答案 0 :(得分:1)

在您的情况下ContentEncodingContentType等。这是返回Json()方法的字段。它发生了,因为它是响应的MVC JSON序列化的一部分,你不需要它。

你应该避免它是创建单独的方法,它会返回你的anonymouse对象(它应该看起来像你的控制器方法,但 没有JSON序列化 )而不是你应该将它传递给控制器​​中的Json()函数。

答案 1 :(得分:1)

假设你有(并且你必须)一个名为People的类:

The program 'node' can be found in the following packages:

 * node

 * nodejs-legacy
Try: apt-get install <selected package>

我删除了'数据',它通常是另一个对象。

现在你构建你的层次结构并像这样序列化p1到json,我已经删除了sid参数。

public class People {
    public int Id { get; set; }
    private string _name;

    public string Name {
        get { return _name + " | " + Id; }
        set { _name = value; }
    }

    public List<People> Children { get; set; }

    public People() {
        Children = new List<People>();
    }
}

这就是诀窍(用http://localhost:50584/Home/CalculateTreeView之类的东西进行测试。)

答案 2 :(得分:1)

您可以生成一个描述结果的类

JSON结果:

{"Name":"Bob","PeopleList":[{"Name":"Tom","PeopleList":[]}]}

C#代码

public class People
{
public string Name { get; set; }
public ICollection<People> PeopleList { get; set; }
public People()
{
PeopleList = new List<People>();
}
}

People people = new People(){Name = "Bob"};
people.PeopleList.Add(new People() { Name = "Tom" });
var s=  Newtonsoft.Json.JsonConvert.SerializeObject(people);

答案 3 :(得分:1)

This is happening because you're using your action method CalculateTreeView with recursion.

[HttpPost]
public JsonResult CalculateTreeView(int sid)
{
/*some code */
    return Json(new { id = res.id, name = res.name + " | " + res.id, data = new {}, children = new object[] { CalculateTreeView(res.l_id) } });
}

Which, in your case, returning a JsonResult instead of raw data to children array ( JsonResult includes parameters like ContentType, ContentEncoding, etc. into your object).

What you need is a helper method which returns and anonymous object. And generate your tree data with recursion inside that helper method.

You Action method: calling recursive helper method and returning JsonResult, which contains ContentType, ContentEncoding and other information about your data.

[HttpPost]
public JsonResult CalculateTreeView(int sid)
{
    return Json(new { json = GenerateTreeViewData(res.l_id) });
}

You Helper method: returning an anonymous object, raw data without ContentType, ContentEncoding, etc. :

private object GenerateTreeViewData(int sid)
{
    if (res != null)
        if (res.l_id != 0)
            return new { id = res.id, name = res.name + " | " + res.id, data = new { }, children = new object[] { GenerateTreeViewData(res.l_id) } };
        else
            return new { id = res.id, name = res.name + " | " + res.id, data = new { }, children = new object[] { } };
    else
        return new { id = res.id, name = res.name + " | " + res.id, data = new { }, children = new object[] { } };
}

UPDATE 1 :

and of course move your "code logic" into recursive helper method"

private object GenerateTreeViewData(int sid)
{
    /*
        Some Code Logic
    */

    if (res != null)
        if (res.l_id != 0)
            return new { id = res.id, name = res.name + " | " + res.id, data = new { }, children = new object[] { GenerateTreeViewData(res.l_id) } };
        else
            return new { id = res.id, name = res.name + " | " + res.id, data = new { }, children = new object[] { } };
    else
        return new { id = res.id, name = res.name + " | " + res.id, data = new { }, children = new object[] { } };
}