How are custom JsonConverter<>
classes used together with System.Text.Json
source generator?
I would like to call JsonSerializer.Deserialize<MyType[]>()
that doesn't fallback to a reflection-based implementation and uses a custom MyTypeJsonParser : JsonConverter<MyType>
.
EDIT to clarify: Custom converter is implemented for MyType
, but json contains an array of MyType
objects. So, I would like to create source generated JsonSerializerContext
that deserializes an array
of MyType
objects (MyType[]
), using generated code to deserialize an array
part and manual converter to deserialize a MyType
objects part.
Old code (that doesn't use a source generator) applies a custom converter, by adding it to JsonSerializerOptions.Converters
.
However, upon further research I found out that Converters
property is missing in JsonSourceGenerationOptionsAttribute
. The tables in documentation also state that JsonConverterAttribute
and JsonSerializerOptions.Converters
are not supported in serialization optimization mode. So, it seems that mixing of custom converters with json source generator is currently (.NET 6) not possible.
The documentation is not clear, whether at least metadata collection source generation mode can use JsonConverterAttribute
.
[JsonConverter(typeof(MyTypeJsonParser))]
on a property? 2)[JsonConverter(typeof(MyTypeJsonParser))]
onMyType
itself? 3) By adding it toJsonSerializerOptions.Converters
? Also, converters are used to manually serialize and deserialize a type, so how would you use a converter together with source generation for automatic serialization? – SupportingJsonSerializerOptions.Converters)
. Custom converter is only forMyType
, but json contains array ofMyType
objects (so source generation would be used for array deserialization and converter for deserialization of MyType objects). Option #2 together withJsonSerializable(typeof(MyType[]))
should work I think. – Hushaby