【发布时间】:2020-08-31 03:04:43
【问题描述】:
我有两个具有相同父类的类,如下所示:
public class Parent
{
public string Name { get; set; } = string.Empty;
public string Type { get; set; } = string.Empty;
}
public class ChildInteger : Parent
{
public int Value { get; set; } = 0;
}
public class ChildDateTime : Parent
{
public DateTime Value { get; set; } = DateTime.MinValue;
}
现在我有一个 API,它返回一个 JSON 字符串类型的数组,其中包含 ChildInteger、ChildDateTime 类型的对象。
JSON 字符串:
[{"Value":1,"Name":"Child Integer 1","Type":"Integer"},{"Value":"2020-08-31T08:29:11.9002559+05:30","Name":"Child DateTime 1","Type":"DateTime"}]
如何反序列化回正确的类型,使值属性不丢失?
-
由于 value 属性丢失,以下方法将不起作用。
列表 parentList1 = new List(); parentList1 = JsonConvert.DeserializeObject
- (json);
注意:这些类来自第三方 API。所以需要在不修改类的情况下实现。
【问题讨论】: