【发布时间】:2020-10-21 06:56:45
【问题描述】:
我收到如下 JSON 响应:
{
"items": [
{
"document": {
"id": "123",
"title": "title2",
"description": "Description1",
"type": "Typ1"
}
},
{
"document": {
"id": "456",
"title": "title2",
"description": "desctiption2",
"type": "Type2",
"Type2Property": "Type2Property"
}
}
]
}
正如您在上面看到的,我有两个具有不同属性的值(仅作为示例)。 在我的代码中,我有两个类。
public class Type1
{
public string Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Type { get; set; }
}
public class Type2
{
public string Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Type { get; set; }
public string Type2Property {get; set;}
}
问题:如何创建一个结合 Type1 和 Type2 的通用列表。未来,我可以拥有更多的TypeX(具有不同的属性)。所以,我想将 JSON 解析成一个通用列表。
更新:我可以通过 JSON 中的 Type 属性过滤 json。
【问题讨论】:
-
通过继承
-
我可以拥有不同属性的不同类。
-
您需要使用类型信息对其进行序列化,而不是使用您自己的 Type 属性 - 请参阅https://stackoverflow.com/questions/6348215/how-to-deserialize-json-into-ienumerablebasetype-with-newtonsoft-json-net
-
从
Type1继承Type2。