JsonSerializer.Serialize only serializes the properties of the base class

Viewed 1804

I would like to have a base class that overrides ToString by converting any objects that inherits it to JSON. When running this program, it seems like this in the context of the base object is not the full object, but instead only the base object itself.

Is it possible to refer to the inherited object from the base object?

using System;
using System.Text.Json;

namespace Test
{
    public class BaseModel 
    {
        public override string ToString() 
        {
            return JsonSerializer.Serialize(this);
        }
    }

    public class Data : BaseModel 
    {
        public string Name { get; set; }
        public int Value { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var data = new Data { Name = "Test", Value = 42 };
            Console.WriteLine(data);
        }
    }
}
2 Answers

This happens because JsonSerialize.Serialize<TValue>(TValue, [JsonSerializerOptions]) is a generic method, and, due to type interference, your code is compiled as:

public override string ToString() 
{
    return JsonSerializer.Serialize<BaseModel>(this);
}

In this case, the solution is to use the non-generic overload JsonSerialize.Serialize(object, Type, [JsonSerializerOptions]) instead:

public override string ToString() 
{
    return JsonSerializer.Serialize(this, this.GetType());
}

You have to define ToString method in the derived class.

public override string ToString()
{
    return JsonSerializer.Serialize(this);
}
Related