3

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?

Andrei
  • 42,814
  • 35
  • 154
  • 218
Francisco Fischer
  • 289
  • 1
  • 4
  • 11
  • 2
    Possible duplicate of [Json.NET serialize object with root name](http://stackoverflow.com/questions/16294963/json-net-serialize-object-with-root-name) – Andrei Jun 02 '16 at 16:05

1 Answers1

9

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/...}
}
Andrei
  • 42,814
  • 35
  • 154
  • 218