Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize into correct child objects

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.
like image 497
Madmenyo Avatar asked Oct 20 '22 12:10

Madmenyo


1 Answers

I had to enable typename handling and pass that to the serializer and deserializer as a settings parameter. I was stuck on this because i was trying to do something like this on my classes.

JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };

string output = JsonConvert.SerializeObject(ProductList, Formatting.Indented, settings);

List<product> deserializedList = JsonConvert.DeserializeObject<List<product>>(output, settings);

Still there should be a option to serialize just the classes you want as for above example i do not need to serialize and store the base/parent class as i already give that type when (de)serializing. I also do not need to serialize the List object, this especially gives unnecessary clutter. So although this is a solution to my problem i am looking for a better way to do this, the following is does not give errors but does not seem to do anything either:

[JsonObject(ItemTypeNameHandling = TypeNameHandling.Objects/all/auto/...)]
class ...
like image 168
Madmenyo Avatar answered Oct 23 '22 09:10

Madmenyo