示例#1
0
        internal static JsonConverter GetConverterForType(Type typeToConvert, JsonSerializerOptions options, bool resolveJsonConverterAttribute = true)
        {
            RootDefaultInstance(); // Ensure default converters are rooted.

            // Priority 1: Attempt to get custom converter from the Converters list.
            JsonConverter?converter = options.GetConverterFromList(typeToConvert);

            // Priority 2: Attempt to get converter from [JsonConverter] on the type being converted.
            if (resolveJsonConverterAttribute && converter == null)
            {
                JsonConverterAttribute?converterAttribute = typeToConvert.GetUniqueCustomAttribute <JsonConverterAttribute>(inherit: false);
                if (converterAttribute != null)
                {
                    converter = GetConverterFromAttribute(converterAttribute, typeToConvert: typeToConvert, memberInfo: null, options);
                }
            }

            // Priority 3: Query the built-in converters.
            converter ??= GetBuiltInConverter(typeToConvert);

            // Expand if factory converter & validate.
            converter = options.ExpandConverterFactory(converter, typeToConvert);
            if (!converter.TypeToConvert.IsInSubtypeRelationshipWith(typeToConvert))
            {
                ThrowHelper.ThrowInvalidOperationException_SerializationConverterNotCompatible(converter.GetType(), converter.TypeToConvert);
            }

            JsonSerializerOptions.CheckConverterNullabilityIsSameAsPropertyType(converter, typeToConvert);
            return(converter);
        }