问题
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