Custom Type Serialization and Deserialization Using Newtonsoft.Json without Attributes

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

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

I would like to do something like:

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

In any case, except for attributes, it would be nice.

+1
source share
1 answer

, Json.Net "ContractResolver", . - DefaultContractResolver. CreateContract . :

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

:

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

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

Source: https://habr.com/ru/post/1648943/


All Articles