usingSystem.Diagnostics.CodeAnalysis;
usingSystem.Reflection;
usingSystem.Text.Json.Reflection;
namespaceSystem.Text.Json.Serialization.Converters
{
[RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")]
internalsealedclassNullableConverterFactory : JsonConverterFactory
{
publicoverrideboolCanConvert(TypetypeToConvert)
{
returntypeToConvert.IsNullableOfT();
}
publicoverrideJsonConverterCreateConverter(TypetypeToConvert, JsonSerializerOptionsoptions)
{
Typetype = typeToConvert.GetGenericArguments()[0];
JsonConverterconverterInternal = options.GetConverterInternal(type);
if (!converterInternal.Type.IsValueType && type.IsValueType)
returnconverterInternal;
returnCreateValueConverter(type, converterInternal);
}
publicstaticJsonConverterCreateValueConverter(TypevalueTypeToConvert, JsonConvertervalueConverter)
{
return (JsonConverter)Activator.CreateInstance(GetNullableConverterType(valueTypeToConvert), BindingFlags.Instance | BindingFlags.Public, null, newobject[1] {
valueConverter
}, null);
}
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2071:UnrecognizedReflectionPattern", Justification = "'NullableConverter<T> where T : struct' implies 'T : new()', so the trimmer is warning calling MakeGenericType here because valueTypeToConvert's constructors are not annotated. But NullableConverter doesn't call new T(), so this is safe.")]
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern", Justification = "'NullableConverter<T> where T : struct' implies 'T : new()', so the trimmer is warning calling MakeGenericType here because valueTypeToConvert's constructors are not annotated. But NullableConverter doesn't call new T(), so this is safe.")]
[return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
privatestaticTypeGetNullableConverterType(TypevalueTypeToConvert)
{
returntypeof(NullableConverter<>).MakeGenericType(valueTypeToConvert);
}
}
}