c# - 使用派生类时,.NET 5 (Newtonsoft) 中的 Json 反序列化失败
问题描述
在尝试反序列化复杂的派生对象 Json 时,该对象实际上是通过在 .NET 5 MVC 中序列化视图模型对象来创建的。我得到派生对象的基类属性变为无效。Viewmodel 中的大多数列表项,如 SelectList、Ienumnerable<> 也变为无效。我尝试了一个简单的继承场景,也有两个属性,不幸的是它也失败了。
有人可以解释如何解决这个问题。
例子
public class Address
{
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode = "99999"; // initialize properties to generate sample data
public Address()
{
}
}
// This will be serialized into a JSON Contact object
public class Contact : Address
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime? BirthDate { get; set; }
public string Phone { get; set; }
public Address Address { get; set; }
public Contact()
{
}
}
public class ContactMain
{
public Contact contact { get; set; }
public ContactMain()
{
// initialize array of objects in default constructor to generate sample data
this.contact = new Contact {
Id = 7113,
Name = "James Norris",
BirthDate = new DateTime(1977, 5, 13),
Phone = "488-555-1212",
Address = new Address
{
Street = "4627 Sunset Ave",
City = "San Diego",
State = "CA",
PostalCode = "92115"
}
};
var jsonString = JsonConvert.SerializeObject(contact);
}
然后尝试反序列化它
JsonConvert.DeserializeObject<Contact>(jsonString);
使 Address Base 类中的所有属性为 null
解决方案
如果要将基类属性用于派生类,则可以直接通过派生类对象调用它们。联系人类的地址属性。
public class Address
{
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode = "99999"; // initialize properties to generate sample data
public Address()
{
}
}
// This will be serialized into a JSON Contact object
public class Contact : Address
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime? BirthDate { get; set; }
public string Phone { get; set; }
public Contact()
{
}
}
public class ContactMain
{
public Contact contact { get; set; }
public ContactMain()
{
// initialize array of objects in default constructor to generate sample data
this.contact = new Contact
{
Id = 7113,
Name = "James Norris",
BirthDate = new DateTime(1977, 5, 13),
Phone = "488-555-1212",
Street = "4627 Sunset Ave",
City = "San Diego",
State = "CA",
PostalCode = "92115"
};
var jsonString = JsonConvert.SerializeObject(contact);
}
}
推荐阅读
- google-cloud-platform - 有没有办法使用 Terraform 将具有“所有者角色”(角色/所有者)的新用户添加到谷歌云项目?
- android - Appium Grid-出现异常:'与远程浏览器通信时出错。它可能已经死了。在其中一台设备中
- javascript - 模块解析失败:您可能需要适当的加载程序来处理此文件类型,目前没有配置加载程序来处理此文件
- c# - 具有讽刺意味的是,解析以空格分隔的列表
- python - 班级要求我为朴素贝叶斯模型 python 提供自我
- c# - 在对象列表中查找某些东西,其中对象值等于字符串
- listview - Xamarin.ListView. How binding working in itemtemplate/datatemplate?
- python - 如何在 textarea 中换行 - django
- javascript - 无论扩展名是什么,JS都显示照片
- javascript - Vue:获取组件列表