【问题标题】:Deserialize Json object with multiple possible child types使用多种可能的子类型反序列化 Json 对象
【发布时间】:2021-09-16 13:07:28
【问题描述】:

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

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

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

【问题讨论】:

标签: c# json asp.net-core json.net


【解决方案1】:

我在 Visual Studio 中测试过,一切正常

var json= ... your json string

var jD = JsonConvert.DeserializeObject<Root>(json);

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 类,但无论如何,在此之后您将需要类从对象转换为类型。如果你不知道对象内部是什么,我无法想象你将如何使用数据

【讨论】:

  • 嗯,这确实解决了我的问题,我想在过滤它时检查 typeof(parameters) 所以我知道我可以用它做什么但是类型已经在父对象中并且当我使用所有那些子对象类型作为某些“大孩子”的接口猜想至少能够使用属性我只需要小心不要对特定子类型使用错误的属性...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-15
  • 2015-12-22
  • 2012-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多