JSON.NET序列与根名字对象 [英] Json.NET serialize object with root name
问题描述
在我的web应用程序,我使用Newtonsoft.Json和我有以下对象
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'
}
}
我知道我可以做到这一点与匿名对象,但任何财产或Newtonsoft.Json图书馆另一种方式?
I know that I can do that with anonymous object, but is any property or another way in Newtonsoft.Json library?
推荐答案
我发现了一个简单的方法来呈现这一点...只是声明了一个动态对象和动态对象中指定的第一个项目是集合类..例如。这假设你使用Newtonsoft.Json
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>();
dynamic collectionWrapper = new {
myRoot = collection
};
var output = JsonConvert.SerializeObject(collectionWrapper);
您应该结束得到的是这样的:
What you should end up with is something like this:
{"myRoot":[{"firstName":"John", "lastName": "Citizen"}, {...}]}
这篇关于JSON.NET序列与根名字对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!