How to add a root node to a JSON in C# using Json.NET?

泄露秘密 提交于 2020-04-14 06:02:50

问题


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.

Supose I have this JSON:

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

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"
        }]
    }
}

How can I do it with C# and JSON.NET?


回答1:


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);

The resulting JSON will look like that:

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


来源:https://stackoverflow.com/questions/37596869/how-to-add-a-root-node-to-a-json-in-c-sharp-using-json-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!