使用派生类时,Json反序列化在.NET 5(Newtonsoft)中失败



在尝试反序列化复杂的派生对象Json时,Json实际上是通过在.NET 5 MVC中序列化视图模型对象创建的。我得到的派生对象的基类属性变为无效。此外,Viewmodel中的大多数列表项,如SelectList、Ienumerable<gt;也将无效。我尝试了一个简单的继承场景,也有2个属性,不幸的是,它也失败了。

有人能解释一下如何解决这个问题吗。

示例

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);

使地址基类中的所有属性为空

如果要将基类属性用于派生类,则可以通过派生类对象直接调用它们。Contact类中的Address属性。

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);
}
} 

相关内容

  • 没有找到相关文章

最新更新