使用 JSON.NET 序列化对象时如何添加自定义根节点?

10

本文介绍了使用 JSON.NET 序列化对象时如何添加自定义根节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我为我的一些对象添加了一个自定义属性,如下所示:

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 序列化对象时如何添加自定义根节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14