I want to create a JsonSerializable class, that I can inherit from. See this code:
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
public interface IJson
{
string ToJson();
}
abstract public class JsonSerializable : IJson
{
public string ToJson()
{
return JsonSerializer.Serialize(this);
}
}
public class Cabinet :JsonSerializable {
[JsonPropertyName("name")]
public string Name { get; set; }
}
I use it as follows:
public class Program
{
public static void Main()
{
var C = new Cabinet();
C.Name = "FOO";
IJson json_thing = C;
Console.WriteLine(JsonSerializer.Serialize(C));
Console.WriteLine(json_thing.ToJson());
}
}
However, the result is:
{"name":"FOO"}
{}
Where I'd think json_thing.ToJson() should also result in {"name":"FOO"}.
Why is the JSON serialization with that extra in between class not working? I want that class in between, because the serialization code for most class will be identical.
JsonSerializer.Serialize<Cabinet>(...)vsJsonSerializer.Serialize<JsonSerializable>(...)class JsonSerializable<T> : IJson where T: JsonSerializable<T>andclass Cabinet : JsonSerializable<Cabinet>so you can doJsonSerializer.Serialize((T)this).