Francisco Fischer Francisco Fischer - 6 months ago 36
JSON Question

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

I am working on

Visual Studio
, 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, to convert to a
XML
I could work with.

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 have this
JSON


{
"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 is it possible?

Answer

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/...}
}
Comments