Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json.NET serialize object with root name

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?

like image 949
user2034092 Avatar asked Apr 30 '13 07:04

user2034092


2 Answers

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); 
like image 171
Andrei Avatar answered Oct 19 '22 14:10

Andrei


I found an easy way to render this out... simply declare a dynamic object and assign the first item within the dynamic object to be your collection class...This example assumes you're using Newtonsoft.Json

private class YourModelClass {     public string firstName { get; set; }     public string lastName { get; set; } }  var collection = new List<YourModelClass>();  var collectionWrapper = new {      myRoot = collection  };  var output = JsonConvert.SerializeObject(collectionWrapper); 

What you should end up with is something like this:

{"myRoot":[{"firstName":"John", "lastName": "Citizen"}, {...}]} 
like image 41
Matthew Merryfull Avatar answered Oct 19 '22 15:10

Matthew Merryfull