Add support for generic JsonConverter instantiation
See original GitHub issueConsider the following value wrapper struct and its associated json converter.
[JsonConverter(typeof(ValueConverter<>))]
struct Value<T>
{
public static implicit operator T(Value<T> value) => value._value;
public static implicit operator Value<T>(T value) => new Value<T>(value);
private readonly T _value;
public Value(T value)
{
_value = value;
}
}
class ValueConverter<T> : JsonConverter
{
public override bool CanConvert(Type objectType) => objectType == typeof(Value<T>);
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) => new Value<T>(serializer.Deserialize<T>(reader));
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => serializer.Serialize(writer, (T)(Value<T>)value, typeof(T));
}
Running the following code I currently get an ArgumentException
of “Invalid type owner for DynamicMethod.”
JsonConvert.SerializeObject(new Value<bool>(true));
Obviously the problem is that the converter type provided with the JsonConverterAttribute
is an open generic type and Json.NET doesn’t know how to instantiate it. The provided converter type is open because currently C#
doesn’t allow use of a types’ type parameters in its attributes.
When an open generic converter type is provided I would like Json.NET to implicitly use the generic type arguments of the type the attribute is applied to using the MakeGenericType
method on Type
in order to instantiate the json converter.
Issue Analytics
- State:
- Created 6 years ago
- Reactions:8
- Comments:17 (10 by maintainers)
I just found a case where I needed this too. Basically, this can be useful any time you want to customize the serialization of a generic type.
I would also find use in this feature. Thanks for providing the custom contract resolver work around.