如何使用Json.NET在C#中向JSON添加根节点? [英] How to add a root node to a JSON in C# using Json.NET?

查看:450
本文介绍了如何使用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/...}
}

这篇关于如何使用Json.NET在C#中向JSON添加根节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆