如何使用Json.NET在C#中向JSON添加根节点?

如何使用Json.NET在C#中向JSON添加根节点?

问题描述:

我正在处理Visual Studio C#项目,我需要将JSON转换为XML. 我收到了字符串格式的JSON. 问题是,如果JSON没有根节点,则我需要在JSON结构中有一个根节点,以便我可以将其转换为具有所需格式的XML.

I am working on Visual Studio C# project and I need to convert a JSON to XML. I receive the JSON in string format. The problem is, I need to have a root node in the JSON structure if the JSON doesn't have one, so that I can convert to XML with desired format.

假设我有这个JSON:

{
        "id": 1,
        "name": {
            "first": "Yong",
            "last": "Mook Kim"
        },
        "contact": [{
            "type": "phone/home",
            "ref": "111-111-1234"
        }, {
            "type": "phone/work",
            "ref": "222-222-2222"
        }]
}

我想像这样将根节点添加到该JSON:

And I want to add root node to that JSON just like that:

{
    "user": {
        "id": 1,
        "name": {
            "first": "Yong",
            "last": "Mook Kim"
        },
        "contact": [{
            "type": "phone/home",
            "ref": "111-111-1234"
        }, {
            "type": "phone/work",
            "ref": "222-222-2222"
        }]
    }
}

我该如何使用C#JSON.NET?

我想您有user对象.只需使用匿名类添加额外的根节点即可:

I suppose you have user object. Just use anonymous class to add extra root node:

var obj = new { user = user };

string json = JsonConvert.SerializeObject(obj);

生成的JSON如下所示:

The resulting JSON will look like that:

{
    "user": {.../your user object/...}
}