I have a class on the C# end that looks something like this:
[DataContract]
public class MyObject
{
[DataMember]
public SomeEnum FooType { get; set; }
[DataMember]
public FooBase MyFoo { get; set; }
}
Where, basically, the value in the property FooType
should tell you what specific type derived from FooBase
is present in the property MyFoo
.
Now if I just wanted to deserialize a object derived from FooBase
I could just do something like:
var myFoo = JsonConvert.DeserializeObject(myJsonString, typeof(FooDerived)) as FooDerived;
But how do I deserialize a MyObject
where the FooBase
object is nested and the information about what type it is can only be determined by partially deserializing the object first?
I'm thinking this is going to need a custom converter derived from JsonConverter, but I'm not entirely sure how to make ReadJson
work here.
Something like this?
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var result = new MyObject();
while(reader.Read())
{
if(reader.TokenType == JsonToken.PropertyName)
{
var prop = reader.Value as string;
if (prop == "FooType")
{
reader.Read();
result.FooType = (SomeEnum)reader.ReadAsInt32(); // or something like that
}
if (prop == "MyFoo")
{
reader.Read();
// now the reader.TokenType should be StartObject, but I can't
// deserialize the object because I don't know what type it is
// I might not have read "FooType" yet
// So I really need to pull this whole sub object out as a string
// and deserialize it later???
}
}
}
return result;
}