使用没有属性的Newtonsoft.Json序列化和反序列化自定义类型 [英] Serialize and deserialize custom type using Newtonsoft.Json without attributes

查看:658
本文介绍了使用没有属性的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);

这篇关于使用没有属性的Newtonsoft.Json序列化和反序列化自定义类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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