1

If I have the following classes:

public class ParentClass
{
    public int ParentProperty { get; set; } = 0;
}
public class ChildClass : ParentClass
{
    public string ChildProperty { get; set; } = "Child property";
}
public class Container
{
    public double ContainerCapacity { get; set; } = 0.2;
    public List<ParentClass> ClassContainer { get; set; } = new List<ParentClass>();
}

And if I then create the following objects in Program.cs:

// Objects
var container = new Container() { ContainerCapacity = 3.14 };
var parent = new ParentClass() { ParentProperty = 5 };
var child = new ChildClass() { ParentProperty = 10, ChildProperty = "value" };
container.ClassContainer.Add(parent);
container.ClassContainer.Add(child);

// Serialization
var serializerOptions = new JsonSerializerOptions() { WriteIndented = true };
var containerJson = JsonSerializer.Serialize(container, serializerOptions);
Console.WriteLine(containerJson);

Expected output:

{
  "ContainerCapacity": 3.14,
  "ClassContainer": [
    {
      "ParentProperty": 5
    },
    {
      "ChildProperty": "value",
      "ParentProperty": 10
    }
  ]
}

Actual output:

{
  "ContainerCapacity": 3.14,
  "ClassContainer": [
    {
      "ParentProperty": 5
    },
    {
      "ParentProperty": 10
    }
  ]
}

How can I make sure that the property ChildProperty on child gets serialized as well? How would I go about it for interface polymorphism?

dbc
  • 104,963
  • 20
  • 228
  • 340
JansthcirlU
  • 688
  • 5
  • 21
  • Do you just need to serialize, or do you also need to **de**serialize? – dbc Nov 08 '20 at 18:08
  • Ideally, both @dbc – JansthcirlU Nov 08 '20 at 19:09
  • Then take a look at [Is polymorphic deserialization possible in System.Text.Json?](https://stackoverflow.com/q/58074304/3744182) and [Is there a simple way to manually serialize/deserialize child objects in a custom converter in System.Text.Json?](https://stackoverflow.com/q/59743382/3744182). But if you only need to serialize, see [Why does System.Text Json Serialiser not serialise this generic property but Json.NET does?](https://stackoverflow.com/a/62033671/3744182) which is simpler. In fact this looks like a duplicate of some or all of those, agree? – dbc Nov 08 '20 at 19:10

1 Answers1

0

I am seeing on the web regarding the issue and it seems it is not doable very easily. I would recommend using Newtonsoft.Json library to parse the objects as it is a mature library and handles the child-parent objects perfectly without an overhead of writing custom settings.

Install nuget package for Newtonsoft.Json and then parse it like this:

var containerJson = JsonConvert.SerializeObject(container, Newtonsoft.Json.Formatting.Indented);

Which gives the output like this:

{
  "ContainerCapacity": 3.14,
  "ClassContainer": [
    {
      "ParentProperty": 5
    },
    {
      "ChildProperty": "value",
      "ParentProperty": 10
    }
  ]
}
Jamshaid K.
  • 3,555
  • 1
  • 27
  • 42