反序列化 Json 具有多种可能子类型的对象

Deserialize Json object with multiple possible child types

我正在尝试反序列化一个基本上具有对象数组的对象,其中每个对象都有一个 属性 对象类型和对象实例。架构看起来有点像这样:

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
}

和Json文件

{
    "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"
            }
        }
    ]
}

那么有没有什么方法可以定义一个不在列表中的所有对象之间共享的泛型类型,甚至一次性反序列化它们? 任何想法表示赞赏。

我在 Visual Studio 中对此进行了测试,一切正常

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; }
}

您可以尝试使用 Dictionary 而不是 Parameters class,但无论如何在这之后您将需要 classes 来从对象转换为类型。如果你不知道对象里面有什么,我无法想象你将如何使用数据