You can use inheritance to cast objects from a subclass to another class.
Given the following json
{
"Name":
{
"first": "bob",
"middle": "john",
"last" : "bobster"
}
}
You can create some C# classes that match the json structure as follows:
public class Model
{
public FullName Name { get; set; }
}
public class Name
{
[JsonProperty("first")]
public string First { get; set; }
[JsonProperty("last")]
public string Last { get; set; }
}
public class FullName : Name
{
[JsonProperty("middle")]
public string Middle { get; set; }
}
Please note that:
FullName
inherits from Name
- class
Model
has a property of type FullName
(i.e. the most specific object)
You can deserialize an object of type Model and then cast the Name
property as follows:
string json = @"{
""Name"":
{
""first"": ""bob"",
""middle"": ""john"",
""last"" : ""bobster""
}
}";
Model model = JsonConvert.DeserializeObject<Model>(json);
Name name = model.Name as Name;
Edit
As an alternative, you can create a generic class as follows
public class Model<TName> where TName : Name
{
public TName Name { get; set; }
}
Deserializing the json:
string json = @"{
""Name"":
{
""first"": ""bob"",
""middle"": ""john"",
""last"" : ""bobster""
}
}";
var fullName = JsonConvert.DeserializeObject<Model<FullName>>(json);
var name = JsonConvert.DeserializeObject<Model<Name>>(json);