I'm trying to deserialize an object that basically has an array of objects where each one has a property with object type and object instance. The schema looks somewhat like this:
public class MainObject
{
public IEnumerable<Parent> Parents { get; set; }
}
public class Parent
{
public string NameOfChildObjectType { get; set; }
public Object Child { get; set; }
}
public class Child_1
{
//some props
}
public class Child_2
{
//some props but different as child 1 or 3
}
public class Child_3
{
// completely different props literally the only thing we have in common is us being children
}
And Json file
{
"id": "1",
"Name": "MainObjectName",
"Parents": [
{
"ChildName": "ChildOfType1",
"Parameters": {
"Name": "Jordan"
}
},
{
"ChildName": "ChildOfType2",
"Parameters": {
"Height": "6`2"
}
},
{
"ChildName": "ChildOfType3",
"Parameters": {
"OwnedPets": [
{
"DogName": "JJ",
"FishName": "Shrimp"
}
],
"MaxHeadRotation": "45"
}
}
]
}
So is there any way I could define a generic type that isn't shared between all the objects in the list or even deserialize them in one go? Any ideas are appreciated.
CodePudding user response:
I tested this in Visual Studio, everything is working properly
var json= ... your json string
var jD = JsonConvert.DeserializeObject<Root>(json);
classes
public class Root
{
public string id { get; set; }
public string Name { get; set; }
public List<Parent> Parents { get; set; }
}
public class OwnedPet
{
public string DogName { get; set; }
public string FishName { get; set; }
}
public class Parameters
{
public string Name { get; set; }
public string Height { get; set; }
public List<OwnedPet> OwnedPets { get; set; }
public string MaxHeadRotation { get; set; }
}
public class Parent
{
public string ChildName { get; set; }
public Parameters Parameters { get; set; }
}
you can try to use Dictionary<string, object> instead of Parameters class, but in any case after this you will need classes to convert from object to type. I can't imagine how are you going to use data if you don't know what is inside of object