我为我的一些对象添加了一个自定义属性,如下所示:
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
我是根据 为 ASP.NET Web API 创建 JSONP 格式化程序.
我没有使用自定义属性,而是重用了 JsonObjectAttribute
的 Title 字段.这是一个使用代码:
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 序列化对象时如何添加自定义根节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!