首页 > 解决方案 > 使用派生类时,.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

标签: c#.netasp.net-mvc.net-corejson.net

解决方案


如果要将基类属性用于派生类,则可以直接通过派生类对象调用它们。联系人类的地址属性。

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

    }
} 

推荐阅读