假设我希望创建一个日记来跟踪婴儿的日常活动。
我有一个名为DiaryEntries的父类(字段:DateTime、PerformBy(
然后我有两个子类:FeedingEntries(字段:FoodType、Volume(DiaperingEntries(字段:PeePop、DiaperBrand(
记录保存在JSON文件中。样品:
{
"entries": [
{
"DateTime": "2020-11-02T21:38:53.4372208+08:00",
"PerformBy": "Jane",
"PeePoop": "Pee",
"DiaperBrand": "Pampers"
},
{
"DateTime": "2020-11-02T21:38:53.4379914+08:00",
"PerformBy": "Andy",
"FoodType": "Milk",
"Volume": "120ml"
},
{
"DateTime": "2020-11-02T21:38:53.438086+08:00",
"PerformBy": "Andy",
"PeePoop": "Poop",
"DiaperBrand": "Diaper"
}
]
}
当我希望返回DiaryEntries及其子类的列表时,如何将此JSON映射到3个对象?
如果我将JSON映射到DiaryEntries对象,那么我只得到DateTime和PerformBy。我试图创建另一个具有所有字段的对象,但我认为这是错误的,因为下次我有另一个条目类型时,我将不得不向该对象添加更多字段。
我不知道有任何方法可以根据找到的属性自动反序列化为不同的子类。相反,为什么不让你的属性更通用呢
{
"entries": [
{
"DateTime": "2020-11-02T21:38:53.4372208+08:00",
"PerformBy": "Jane",
"Activity": "Pee",
"Details": "Pampers"
},
{
"DateTime": "2020-11-02T21:38:53.4379914+08:00",
"PerformBy": "Andy",
"Activity": "Milk",
"Details": "120ml"
},
{
"DateTime": "2020-11-02T21:38:53.438086+08:00",
"PerformBy": "Andy",
"Activity": "Poop",
"Details": "Diaper"
}
] }
那么您实际上只需要一个具有DateTime、PerformBy、Activity和Details属性的类。活动&详细信息可以是枚举,以便在需要时以编程方式区分它们。
根据您的描述,下面的Jason是有效的,我假设子类将被列出。
{
"entries": [
{
"DateTime": "2020-11-02T21:38:53.4372208+08:00",
"PerformBy": "Jane",
"DiaperingEntries ":[{
"PeePoop": "Pee",
"DiaperBrand": "Pampers"
}]
},
{
"DateTime": "2020-11-02T21:38:53.4379914+08:00",
"PerformBy": "Andy",
"FeedingEntries":[{
"FoodType": "Milk",
"Volume": "120ml"
}]
},
{
"DateTime": "2020-11-02T21:38:53.438086+08:00",
"PerformBy": "Andy",
"DiaperingEntries ":[{
"PeePoop": "Poop",
"DiaperBrand": "Diaper"
}]
}
]
}
您可以将所有内容反序列化为基本对象,并根据需要进行强制转换。