While trying to deserialize a complex derived object Json, which is actually created by serializing a viewmodel object in .NET 5 MVC. I am getting the base class properties of the derived object becomes nullified. Also most of the list items in the Viewmodel like SelectList, Ienumnerable<> also become nullified. I tried with a simple inheritance scenario also with 2 properties, unfortunately then also it failed.
Can someone explain how to solve this.
Example
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);
}
Then trying to deserialze it with
JsonConvert.DeserializeObject<Contact>(jsonString);
Makes all the properties in Address Base class null
If you want to use base class property to derived class then you can directly call them by derived class object. Address property from Contact class.
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);
}
}