One way to deserialize an interface and abstract properties is to use a class that sets TypeNameHandling to Auto during serialization and deserialization. However, when I try to do the same when serializing and deserializing the interface object directly, it does not work -
interface ISample { string Key { get; set; } } class A : ISample { public string Key { get; set; } public A(string key) { this.Key = key; } } class B : ISample { public string Key { get; set; } public B(string key) { this.Key = key; } }
The serialization and deserialization code is
ISample a = new A("keyA"); ISample b = new B("keyB"); var settings = new JsonSerializerSettings(); settings.TypeNameHandling = TypeNameHandling.Auto; var stringA = JsonConvert.SerializeObject(a, settings); var stringB = JsonConvert.SerializeObject(b, settings); Console.WriteLine(stringA); Console.WriteLine(stringB); a = JsonConvert.DeserializeObject<ISample>(stringA, settings); b = JsonConvert.DeserializeObject<ISample>(stringB, settings);
I noticed that even when setting TypeNameHandling.Auto, type information is not in the serialized string. However, the TypeNameHandling settings for Object or All work.
Did I miss something basic here?
ambivi
source share