Class JsonInterfaceConverter<T>
- Namespace
- VisioForge.Core.Types.Helpers
- Assembly
- VisioForge.Core.dll
A custom JSON converter that enables polymorphic serialization and deserialization of interface types and abstract classes using System.Text.Json.
public class JsonInterfaceConverter<T> : JsonConverter<T> where T : classType Parameters
T-
The interface or abstract class type to convert.
Inheritance
Inherited Members
Remarks
This converter adds type information to the JSON output by including a "$type" property that contains the full type name of the concrete implementation. During deserialization, it uses this type information to instantiate the correct concrete type.
This is particularly useful when serializing collections of interface types or when the exact runtime type needs to be preserved across serialization boundaries.
Example usage:
var options = new JsonSerializerOptions();
options.Converters.Add(new JsonInterfaceConverter<IMyInterface>());
var json = JsonSerializer.Serialize(myInterfaceInstance, options);
Note: The converter only works with types from the same assembly. For cross-assembly scenarios, additional type resolution logic may be needed.
Methods
Read(ref Utf8JsonReader, Type, JsonSerializerOptions)
Reads and converts the JSON to type T.
public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)Parameters
readerUtf8JsonReader-
The reader positioned at the start of the JSON to convert.
typeToConvertType-
The type to convert to (will be T or a derived type).
optionsJsonSerializerOptions-
An object that specifies serialization options to use.
Returns
- T
-
The deserialized object of the concrete type specified in the JSON.
Exceptions
- JsonException
-
Thrown when the JSON is not properly formatted, missing the $type property, or when the specified type cannot be instantiated.
Write(Utf8JsonWriter, T, JsonSerializerOptions)
Writes a specified value as JSON with type information.
public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)Parameters
writerUtf8JsonWriter-
The writer to write JSON to.
valueT-
The value to convert to JSON. Can be null.
optionsJsonSerializerOptions-
An object that specifies serialization options to use.
Remarks
This method adds a "$type" property containing the full type name of the value's runtime type. If the value is null, it serializes as a JSON null without type information. The type information enables proper deserialization to the correct concrete type.