| | | 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.CodeAnalysis; |
| | | 5 | | using System.Reflection; |
| | | 6 | | |
| | | 7 | | namespace System.Text.Json.Serialization.Converters |
| | | 8 | | { |
| | | 9 | | [RequiresDynamicCode(JsonSerializer.SerializationRequiresDynamicCodeMessage)] |
| | | 10 | | [RequiresUnreferencedCode(JsonSerializer.SerializationUnreferencedCodeMessage)] |
| | | 11 | | internal sealed class JsonUnionConverterFactory : JsonConverterFactory |
| | | 12 | | { |
| | | 13 | | private const string UnionAttributeName = "UnionAttribute"; |
| | | 14 | | private const string UnionAttributeFullName = "System.Runtime.CompilerServices.UnionAttribute"; |
| | | 15 | | |
| | | 16 | | // A type IS a union iff it carries [System.Runtime.CompilerServices.UnionAttribute]. |
| | | 17 | | // The marker is detected by full name (rather than via a compile-time reference) |
| | | 18 | | // because the C# compiler may polyfill it into the user's assembly when targeting a |
| | | 19 | | // downlevel runtime. [JsonUnion] alone is a customization attribute that has no meaning |
| | | 20 | | // on non-union types. |
| | 0 | 21 | | public override bool CanConvert(Type typeToConvert) => IsUnionType(typeToConvert); |
| | | 22 | | |
| | | 23 | | public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) |
| | 0 | 24 | | { |
| | 0 | 25 | | Type converterType = typeof(JsonUnionConverter<>).MakeGenericType(typeToConvert); |
| | 0 | 26 | | return (JsonConverter)Activator.CreateInstance(converterType)!; |
| | 0 | 27 | | } |
| | | 28 | | |
| | | 29 | | private static bool IsUnionType(Type type) |
| | 0 | 30 | | { |
| | 0 | 31 | | foreach (CustomAttributeData data in type.GetCustomAttributesData()) |
| | 0 | 32 | | { |
| | 0 | 33 | | Type attributeType = data.AttributeType; |
| | 0 | 34 | | if (attributeType.Name == UnionAttributeName && |
| | 0 | 35 | | attributeType.FullName == UnionAttributeFullName) |
| | 0 | 36 | | { |
| | 0 | 37 | | return true; |
| | | 38 | | } |
| | 0 | 39 | | } |
| | | 40 | | |
| | 0 | 41 | | return false; |
| | 0 | 42 | | } |
| | | 43 | | } |
| | | 44 | | } |
| | | 45 | | |