I am trying to deserialize a mix of a parent and different childs into a List<parent>
. Unfortunately all the extra fields of my childs get discarded and are being serialized as a parent.
I have been trying to figure out how to name the objects as a whole to link them to the correct child class. I did not have any results with this.
These are a simple parent and child class i try to serialize objects from:
[JsonObject(MemberSerialization.OptIn)]
class Product
{
[JsonProperty]
public string Name { get; set; }
[JsonProperty]
public int Amount { get; set; }
[JsonProperty]
public int Value { get; set; }
}
[JsonObject(MemberSerialization.OptIn)]
class ProductType : Product
{
[JsonProperty(Order = 4)]
public int Volume { get; set; }
}
Serializing is not a problem, volume gets added as final field for the "special product" object. The goal is to have multiple childs. Below the code that serializes 2 created objects in a list. It fails deserializing as it puts both objects back as a normal product in the list:
Product test1 = new Product { Name = "Simple Product", Amount = 110, Value = 10 };
ProductType test2 = new ProductType { Name= "Special Type", Amount = 230, Value = 22, Volume = 6 };
List<Product> ProductList = new List<Product>() { test1, test2 };
string output = JsonConvert.SerializeObject(ProductList, Formatting.Indented); //Works correctly.
List<Product> DeSerialized = JsonConvert.DeserializeObject<List<Product>>(output); //Fails creating child object.