I wanted to deserialize JSON that was not serialized by my application, so I needed to specify a specific implementation manually. I expanded Nicholas's answer.
Assume that
public class Person { public ILocation Location { get;set; } }
and concrete example
public class Location: ILocation { public string Address1 { get; set; }
Add to this class.
public class ConfigConverter<I, T> : JsonConverter { public override bool CanWrite => false; public override bool CanRead => true; public override bool CanConvert(Type objectType) { return objectType == typeof(I); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new InvalidOperationException("Use default serialization."); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var jsonObject = JObject.Load(reader); var deserialized = (T)Activator.CreateInstance(typeof(T)); serializer.Populate(jsonObject.CreateReader(), deserialized); return deserialized; } }
Then define your interfaces with the JsonConverter attribute
public class Person { [JsonConverter(typeof(ConfigConverter<ILocation, Location>))] public ILocation Location { get;set; } }
Adam Pedley Feb 16 '17 at 6:18 2017-02-16 06:18
source share