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

查看:150
本文介绍了在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());

我这个code问题是,我需要介绍一下我的自定义转换器在每一个序列化/反序列化。在我的项目有很多情况下,我不能这样做。举例来说,我使用的利用Json.Net,以及他们将工作在我的 SomeClass的实例等外部项目。但因为我不想或无法使他们的code修改,我也没办法介绍我的转换器。

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所以无论身在何处序列化/反序列化的情况,我的转换器总是present?

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或更高版本。见<一href=\"http://james.newtonking.com/json/help/?topic=html/P_Newtonsoft_Json_JsonConvert_DefaultSettings.htm\"><$c$c>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天全站免登陆