Class JsonInterfaceConverterAttribute
- Namespace
- VisioForge.Core.Types.Helpers
- Assembly
- VisioForge.Core.dll
Specifies that an interface type should use a custom JSON converter for polymorphic serialization.
[AttributeUsage(AttributeTargets.Interface, AllowMultiple = false)]
public class JsonInterfaceConverterAttribute : JsonConverterAttributeInheritance
Inherited Members
Examples
// Define an interface with the converter attribute
[JsonInterfaceConverter(typeof(JsonInterfaceConverter<IMyInterface>))]
public interface IMyInterface
{
string Name { get; set; }
}
// Implement the interface
public class ConcreteImplementation : IMyInterface
{
public string Name { get; set; }
public int Value { get; set; }
}
// Serialize and deserialize
var obj = new ConcreteImplementation { Name = "Test", Value = 42 };
string json = JsonSerializer.Serialize<IMyInterface>(obj);
// Result: {"$type":"ConcreteImplementation","Name":"Test","Value":42}
IMyInterface deserialized = JsonSerializer.Deserialize<IMyInterface>(json);
// Correctly creates a ConcreteImplementation instance
Remarks
This attribute is specifically designed for interface types that need polymorphic JSON serialization using System.Text.Json. When applied to an interface, it instructs the serializer to use the specified converter to handle serialization and deserialization of all implementations of that interface.
Key Features:
- Automatically applied to all properties/fields of the interface type
- Works with VisioForge.Core.Types.Helpers.JsonInterfaceConverter`1 to preserve type information
- Enables collections of interface types to serialize with concrete type information
- Only one converter can be specified per interface (AllowMultiple = false)
This attribute extends JsonConverterAttribute to provide the same functionality but with restrictions appropriate for interface types. It can only be applied to interfaces, not classes or other types.
Constructors
JsonInterfaceConverterAttribute(Type)
Initializes a new instance of the VisioForge.Core.Types.Helpers.JsonInterfaceConverterAttribute class with the specified converter type.
public JsonInterfaceConverterAttribute(Type converterType)Parameters
converterTypeType-
The type of the JSON converter to use for this interface. Must be a type that inherits from JsonConverter and is compatible with the interface type. Typically should be VisioForge.Core.Types.Helpers.JsonInterfaceConverter`1 with the interface as the type parameter.
Remarks
The converter type should be constructed as typeof(JsonInterfaceConverter<IYourInterface>)
where IYourInterface is the interface being decorated with this attribute. The converter
will handle serialization and deserialization of all implementations of the interface.
Exceptions
- ArgumentNullException
-
Thrown if
converterTypeis null. - InvalidOperationException
-
Thrown during serialization if the converter type is not compatible with the interface type.