| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.Diagnostics; |
| | | 5 | | using System.Diagnostics.CodeAnalysis; |
| | | 6 | | using System.Reflection; |
| | | 7 | | using System.Text.Json.Reflection; |
| | | 8 | | |
| | | 9 | | namespace System.Text.Json.Serialization.Converters |
| | | 10 | | { |
| | | 11 | | [RequiresDynamicCode(JsonSerializer.SerializationRequiresDynamicCodeMessage)] |
| | | 12 | | internal sealed class NullableConverterFactory : JsonConverterFactory |
| | | 13 | | { |
| | | 14 | | public override bool CanConvert(Type typeToConvert) |
| | 3646 | 15 | | { |
| | 3646 | 16 | | return typeToConvert.IsNullableOfT(); |
| | 3646 | 17 | | } |
| | | 18 | | |
| | | 19 | | public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) |
| | 0 | 20 | | { |
| | 0 | 21 | | Debug.Assert(typeToConvert.IsNullableOfT()); |
| | | 22 | | |
| | 0 | 23 | | Type valueTypeToConvert = typeToConvert.GetGenericArguments()[0]; |
| | 0 | 24 | | JsonConverter valueConverter = options.GetConverterInternal(valueTypeToConvert); |
| | | 25 | | |
| | | 26 | | // If the value type has an interface or object converter, just return that converter directly. |
| | 0 | 27 | | if (!valueConverter.Type!.IsValueType && valueTypeToConvert.IsValueType) |
| | 0 | 28 | | { |
| | 0 | 29 | | return valueConverter; |
| | | 30 | | } |
| | | 31 | | |
| | 0 | 32 | | return CreateValueConverter(valueTypeToConvert, valueConverter); |
| | 0 | 33 | | } |
| | | 34 | | |
| | | 35 | | public static JsonConverter CreateValueConverter(Type valueTypeToConvert, JsonConverter valueConverter) |
| | 0 | 36 | | { |
| | 0 | 37 | | Debug.Assert(valueTypeToConvert.IsValueType && !valueTypeToConvert.IsNullableOfT()); |
| | 0 | 38 | | return (JsonConverter)Activator.CreateInstance( |
| | 0 | 39 | | GetNullableConverterType(valueTypeToConvert), |
| | 0 | 40 | | BindingFlags.Instance | BindingFlags.Public, |
| | 0 | 41 | | binder: null, |
| | 0 | 42 | | args: new object[] { valueConverter }, |
| | 0 | 43 | | culture: null)!; |
| | 0 | 44 | | } |
| | | 45 | | |
| | | 46 | | [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2071:UnrecognizedReflectionPattern", |
| | | 47 | | Justification = "'NullableConverter<T> where T : struct' implies 'T : new()', so the trimmer is warning call |
| | | 48 | | "But NullableConverter doesn't call new T(), so this is safe.")] |
| | | 49 | | [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] |
| | 0 | 50 | | private static Type GetNullableConverterType(Type valueTypeToConvert) => typeof(NullableConverter<>).MakeGeneric |
| | | 51 | | } |
| | | 52 | | } |