How can I add a custom root node when serializing an object with JSON.NET?(使用 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
我是根据 为 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 = "dXNlcg==")]
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 序列化对象时如何添加自定义根节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 JSON.NET 序列化对象时如何添加自定义根节点?


- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 使用 rss + c# 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01