Json.NET serialize object with root name

user2034092 picture user2034092 · Apr 30, 2013 · Viewed 124.1k times · Source

In my web app I'm using Newtonsoft.Json and I have following object

[Newtonsoft.Json.JsonObject(Title = "MyCar")]
public class Car
{
    [Newtonsoft.Json.JsonProperty(PropertyName = "name")]
    public string Name{get;set;}

    [Newtonsoft.Json.JsonProperty(PropertyName = "owner")]
    public string Owner{get;set;}
}

and I want serialize them with root name (class name). This is desired format using

{'MyCar':
 {
   'name': 'Ford',
   'owner': 'John Smith'
 }
}

I know that I can do that with anonymous object, but is any property or another way in Newtonsoft.Json library?

Answer

Andrei picture Andrei · Apr 30, 2013

Use anonymous class

Shape your model the way you want using anonymous classes:

var root = new 
{ 
    car = new 
    { 
        name = "Ford", 
        owner = "Henry"
    }
};

string json = JsonConvert.SerializeObject(root);