maybe a similar question has already been answered somewhere else. But I've spent a lot of time to look for it and to try getting a solution. So I hope someone can help.
I have a class
public class SampleClass
{
public int Id {get;set;}
public string TypeName {get;set;}
public BaseClass Data {get;set;}
}
Then I have several "data" classes derived from BaseClass, for example:
public class DataClass: BaseClass
{
public string Name {get;set;}
public string Address {get;set;}
}
Serialization works fine.
var sample = new SampleClass();
sample.Id = 1;
sample.TypeName = "DataClass";
var data = new DataClass();
data.Name = "Test";
data.Address = "Address";
sample.Data = data;
var jsonString = JsonConvert.SerializeObject(sample);
Result: {"Id":1,"TypeName":"DataClass","Data":{"Name":"Test","Address":"Address"}}
But the way back brings an empty "Data" property:
var backToObject = JsonConvert.DeserializeObject<SampleClass>(jsonString);
Is there a way to tell the Json converter that it should deserialize "Data" into the type given in "TypeName"?
JsonConverterto deserialize your class hierarchy. Please see Deserializing polymorphic json classes without type information using json.net, Json.Net Serialization of Type with Polymorphic Child Object or How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects? for details.TypeNameproperty insideBaseClassrather thanSampleClasssoBaseClassis self-contained and can be reused elsewhere.