Thursday, February 10, 2022

System.Text.Json.JsonSerializer: Serialize Properties of Derived Classes

Did you know by default JsonSerializer doesn't serialize Properties of Derived Classes?

Say we have the following classes.

public class Person
{
    public string Name { getset; }
}
 
public class Student : Person
{
    public int StudentId { getset; }
}

I am creating a Student, but I am assigning it to a Person.

Person person = new Student
{
    Name = "John Doe",
    StudentId = 1
};

Now if I serialize this using Json.NET,

var options = new Newtonsoft.Json.JsonSerializerSettings
{
    Formatting = Newtonsoft.Json.Formatting.Indented,
};
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(person, options));

I am getting the following output. The correct underline type is serialized.

{
  "StudentId": 1,
  "Name""John Doe"
}

Now if I serialize the same using JsonSerializer,

var options = new System.Text.Json.JsonSerializerOptions { WriteIndented = true };
Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(person, options));

I am getting the following output. You can see it has only serialized the properties that are in the Parent class.

{
  "Name""John Doe"
}

Now we can change this behavior using one of two ways.

  1. Call an overload of Serialize and ask to use type at run time
  2. Declare the object to be serialized as an object

var options = new System.Text.Json.JsonSerializerOptions { WriteIndented = true };

// Call an overload of Serialize that lets you specify the type at run time:
Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(person, person.GetType(), options));

// Declare the object to be serialized as object
Console.WriteLine(System.Text.Json.JsonSerializer.Serialize<object>(person, options));

And now we can see the correct underline type is getting serialized.

{
  "StudentId": 1,
  "Name""John Doe"
}

Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment