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?
Shape your model the way you want using anonymous classes:
var root = new { car = new { name = "Ford", owner = "Henry" } }; string json = JsonConvert.SerializeObject(root);
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"}, {...}]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With