在 Json.Net 中全局注册自定义 JsonConverter [英] Registering a custom JsonConverter globally in Json.Net

查看:25
本文介绍了在 Json.Net 中全局注册自定义 JsonConverter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Json.Net,我的对象中有一些属性需要特别注意才能序列化/反序列化它们.作为 JsonConverter 的后代,我成功地做到了这一点.这是执行此操作的常用方法:

Using Json.Net, I have properties in my objects which need special care in order to serialize / deserialize them. Making a descendant of JsonConverter, I managed to accomplish this successfully. This is the common way of doing this:

public class SomeConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        ...
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        ...
    }

    public override bool CanConvert(Type objectType)
    {
        ...
    }
}

class SomeClass
{
    [JsonProperty, JsonConverter(typeof(SomeConverter))]
    public SomeType SomeProperty;
}

//Later on, in code somewhere
SomeClass SomeObject = new SomeClass();
string json = JsonConvert.SerializeObject(SomeObject, new SomeConverter());

我对这段代码的问题是我需要在每个序列化/反序列化中引入我的自定义转换器.在我的项目中,有很多情况我无法做到这一点.例如,我正在使用其他使用 Json.Net 的外部项目,它们将在我的 SomeClass 实例上工作.但由于我不想或不能更改他们的代码,所以我无法介绍我的转换器.

My problem with this code is that I need to introduce my custom converter in every serialization / deserialization. In my project there are many cases that I cannot do that. For instance, I'm using other external projects which make use of Json.Net as well and they will be working on my SomeClass instances. But since I don't want to or can't make change in their code, I have no way to introduce my converter.

有什么方法可以在 Json.Net 中使用一些 static 成员注册我的转换器,所以无论序列化/反序列化发生在哪里,我的转换器始终存在?

Is there any way I can register my converter, using some static member perhaps, in Json.Net so no matter where serialization / deserialization happens, my converter is always present?

推荐答案

是的,这可以使用 Json.Net 5.0.5 或更高版本.请参阅 JsonConvert.DefaultSettings.

Yes, this is possible using Json.Net 5.0.5 or later. See JsonConvert.DefaultSettings.

JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
    Converters = new List<JsonConverter> { new SomeConverter() }
};

// Later on...
string json = JsonConvert.SerializeObject(someObject);  // this will use SomeConverter

如果您使用的是 Web API,则可以像这样在全局范围内设置转换器:

If you're using Web API, you can set up a converter globally like this instead:

var config = GlobalConfiguration.Configuration;
var jsonSettings = config.Formatters.JsonFormatter.SerializerSettings;
jsonSettings.Converters.Add(new SomeConverter());

这篇关于在 Json.Net 中全局注册自定义 JsonConverter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆