使用JSON.NET序列化对象时,如何添加自定义根节点? [英] How can I add a custom root node when serializing an object with JSON.NET?
问题描述
我已经向某些对象添加了自定义属性,如下所示:
I have added a custom property to some of my objects like this:
[JsonCustomRoot("status")]
public class StatusDTO
{
public int StatusId { get; set; }
public string Name { get; set; }
public DateTime Created { get; set; }
}
该属性非常简单:
public class JsonCustomRoot :Attribute
{
public string rootName { get; set; }
public JsonCustomRoot(string rootName)
{
this.rootName = rootName;
}
}
序列化对象实例时,JSON.NET的默认输出是:
The default output from JSON.NET when serializing an instance of an object is this:
{"StatusId":70,"Name":"Closed","Created":"2012-12-12T11:50:56.6207193Z"}
现在的问题是:如何使用自定义属性的值向JSON添加根节点:
{status:{"StatusId":70,"Name":"Closed","Created":"2012-12-12T11:50:56.6207193Z"}}
我发现有几篇文章提到 IContractResolver 界面,但我不知道该怎么做.我的尝试包括这段未完成的代码:
I have found several articles mentioning the IContractResolver interface, but I cannot grasp how to do it. My attempts include this unfinished piece of code:
protected override JsonObjectContract CreateObjectContract(Type objectType)
{
JsonObjectContract contract = base.CreateObjectContract(objectType);
var info = objectType.GetCustomAttributes()
.SingleOrDefault(t => (Type)t.TypeId==typeof(JsonCustomRoot));
if (info != null)
{
var myAttribute = (JsonCustomRoot)info;
// How can i add myAttribute.rootName to the root from here?
// Maybe some other method should be overrided instead?
}
return contract;
}
推荐答案
这是专门针对Web API的解决方案,我也在使用: RootFormatter .cs
Here's a solution specifically for Web API, which I am also using: RootFormatter.cs
我基于我没有使用自定义属性,而是重用了JsonObjectAttribute
的标题"字段.这是一个用法代码:
Instead of using a custom attribute I am reusing Title field of JsonObjectAttribute
. Here's a usage code:
using Newtonsoft.Json
[JsonObject(Title = "user")]
public class User
{
public string mail { get; set; }
}
然后,将RootFormatter添加到您的App_Start中,并在WebApiConfig
中进行如下注册:
Then, add RootFormatter to your App_Start and register it as follows in WebApiConfig
:
GlobalConfiguration.Configuration.Formatters.Insert(0, new RootFormatter());
我能够得到类似于WCF WebMessageBodyStyle.Wrapped
的包装响应:
I was able to get a wrapped response similar to WCF's WebMessageBodyStyle.Wrapped
:
{"user":{
"mail": "foo@example.com"
}}
这篇关于使用JSON.NET序列化对象时,如何添加自定义根节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!