使用没有属性的Newtonsoft.Json序列化和反序列化自定义类型

使用没有属性的Newtonsoft.Json序列化和反序列化自定义类型

问题描述:

我知道有些JsonConverters可用于自定义序列化/反序列化. 但是我不想通过属性,而是通过代码来应用它.

I know that there are JsonConverters that I can use for custom serialization/deserialization. But I do not want to apply this via attributes, rather via code.

我的框架具有对序列化程序的插件支持,现在我要添加Newtonsoft JSON支持. 因此,我不想将特定于newtonsoft的属性添加到我的类型中. 是否可以通过其他任何方式将JsonConverter应用于特定类型?

My framework has plugin support for serializers and I'm about to add Newtonsoft JSON support now. And thus, I do not want to add attributes specific for newtonsoft to my types. Is there any way to apply a JsonConverter to a specific type in any other way?

我想按照以下方式做些事情:

I would like to do something along the lines of:

  serializer.AddTypeHandler(typeof(MyType), serializeFunction, deserializeFunction);

除attribs以外的任何方式都很好..

Any way except attribs would be nice..

是的,Json.Net具有可用于此目的的"ContractResolver"概念.制作自定义解析器的最简单方法是从DefaultContractResolver继承.然后,您可以覆盖CreateContract方法,以根据需要将转换器应用于特定类型.例如:

Yes, Json.Net has the concept of a "ContractResolver" that can be used for this purpose. The easiest way to make a custom resolver is to inherit from DefaultContractResolver. Then you can override the CreateContract method to apply converters to specific types as needed. For example:

class CustomResolver : DefaultContractResolver
{
    protected override JsonContract CreateContract(Type objectType)
    {
        JsonContract contract = base.CreateContract(objectType);
        if (objectType == typeof(Foo))
        {
            contract.Converter = new FooConverter();
        }
        return contract;
    }
}

您可以将解析器应用于序列化器,如下所示:

You can apply the resolver to the serializer like this:

JsonSerializerSettings settings = new JsonSerializerSettings
{
    ContractResolver = new CustomResolver()
};

string json = JsonConvert.SerializeObject(foo, settings);