iTranslated by AI
The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
👏
Creating a Generic JsonConverter for Interfaces in System.Text.Json
Introduction
I will introduce how to create a generic converter to serialize and deserialize classes that implement interfaces like the following using System.Text.Json.
public interface IEmployee
{
int EmployeeId { get; }
}
public class Employee : IEmployee
{
public Employee(int employeeId)
{
EmployeeId = employeeId;
}
public int EmployeeId { get; }
}
That being said, since serialization works out of the box, the main focus here is deserialization.
Implementing the Converter
Prepare a custom implementation of System.Text.Json.Serialization.JsonConverter.
public class InterfaceConverter<TInterface, TImplement>
: JsonConverter<TInterface> where TImplement : TInterface
{
public override TInterface Read(
ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options)
{
return (TInterface)JsonSerializer.Deserialize(ref reader, typeof(TImplement), options);
}
public override void Write(
Utf8JsonWriter writer,
TInterface value,
JsonSerializerOptions options)
{
JsonSerializer.Serialize(writer, value, typeof(TImplement), options);
}
}
Using the Converter
You can use it like this:
var employee = (IEmployee)new Employee(100);
var options = new JsonSerializerOptions
{
Converters =
{
new InterfaceConverter<IEmployee, Employee>()
}
};
var employeeString = JsonSerializer.Serialize(employee, options);
Console.WriteLine(employeeString);
var deserializedUnit = JsonSerializer.Deserialize<IEmployee>(employeeString, options);
That's it!
Discussion