Serialize and deserialize custom type using Newtonsoft.Json without attributes

試著忘記壹切 提交于 2019-12-11 06:53:10

问题


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.

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);

Any way except attribs would be nice..


回答1:


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);


来源:https://stackoverflow.com/questions/22268478/serialize-and-deserialize-custom-type-using-newtonsoft-json-without-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!