Skip to content

Commit af64b38

Browse files
Narrow union number handling fix
Co-authored-by: eiriktsarpalis <[email protected]>
1 parent e429472 commit af64b38

4 files changed

Lines changed: 49 additions & 85 deletions

File tree

‎src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Union/JsonUnionConverter.cs‎

Lines changed: 7 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -66,15 +66,15 @@ internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert,
6666
}
6767
else
6868
{
69-
if (!TryResolveCaseType(ref reader, typeToConvert, typeInfo, state.Current.NumberHandling, out caseType))
69+
if (!TryResolveCaseType(ref reader, typeToConvert, typeInfo, out caseType))
7070
{
7171
value = default;
7272
return false;
7373
}
7474

7575
caseTypeInfo = options.GetTypeInfoInternal(caseType);
7676
state.Current.JsonPropertyInfo = caseTypeInfo.PropertyInfoForTypeInfo;
77-
state.Current.NumberHandling ??= caseTypeInfo.NumberHandling ?? options.NumberHandling;
77+
state.Current.NumberHandling ??= caseTypeInfo.NumberHandling;
7878
}
7979

8080
JsonConverter caseConverter = caseTypeInfo.Converter;
@@ -88,12 +88,7 @@ internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert,
8888
return true;
8989
}
9090

91-
private static bool TryResolveCaseType(
92-
ref Utf8JsonReader reader,
93-
Type typeToConvert,
94-
JsonTypeInfo<TUnion> typeInfo,
95-
JsonNumberHandling? numberHandling,
96-
out Type caseType)
91+
private static bool TryResolveCaseType(ref Utf8JsonReader reader, Type typeToConvert, JsonTypeInfo<TUnion> typeInfo, out Type caseType)
9792
{
9893
caseType = null!;
9994
JsonTypeClassifier? classifier = typeInfo.TypeClassifier;
@@ -123,23 +118,13 @@ private static bool TryResolveCaseType(
123118
JsonTokenType tokenType = reader.TokenType;
124119
JsonValueType valueType = GetJsonValueType(tokenType);
125120

126-
Type? resolvedCaseType = null;
127-
bool isAmbiguous;
128-
if (numberHandling == typeInfo.NumberHandling)
129-
{
130-
isAmbiguous = (typeInfo.UnionAmbiguousValueTypes & valueType) != 0;
131-
typeInfo.UnionValueTypeMap?.TryGetValue(valueType, out resolvedCaseType);
132-
}
133-
else
134-
{
135-
resolvedCaseType = typeInfo.ResolveUnionCaseType(valueType, numberHandling, out isAmbiguous);
136-
}
137-
138-
if (isAmbiguous)
121+
if ((typeInfo.UnionAmbiguousValueTypes & valueType) != 0)
139122
{
140123
ThrowHelper.ThrowJsonException_UnionAmbiguousJsonValueType(typeToConvert, valueType);
141124
}
142125

126+
Type? resolvedCaseType = null;
127+
typeInfo.UnionValueTypeMap?.TryGetValue(valueType, out resolvedCaseType);
143128
caseType = resolvedCaseType!;
144129
}
145130

@@ -201,7 +186,7 @@ internal override bool OnTryWrite(Utf8JsonWriter writer, TUnion value, JsonSeria
201186

202187
JsonTypeInfo caseTypeInfo = options.GetTypeInfoInternal(caseType);
203188
state.Current.JsonPropertyInfo = caseTypeInfo.PropertyInfoForTypeInfo;
204-
state.Current.NumberHandling ??= caseTypeInfo.NumberHandling ?? options.NumberHandling;
189+
state.Current.NumberHandling ??= caseTypeInfo.NumberHandling;
205190
return caseTypeInfo.Converter.TryWriteAsObject(writer, caseValue, options, ref state);
206191
}
207192
}

‎src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Metadata/JsonTypeInfo.cs‎

Lines changed: 1 addition & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1163,7 +1163,6 @@ private static void BuildUnionValueTypeMap(IList<JsonUnionCaseInfo> unionCases,
11631163
{
11641164
var map = new Dictionary<JsonValueType, Type>();
11651165
JsonValueType ambiguousValueTypes = JsonValueType.None;
1166-
JsonNumberHandling? unionNumberHandling = target.NumberHandling;
11671166

11681167
foreach (JsonUnionCaseInfo info in unionCases)
11691168
{
@@ -1176,7 +1175,7 @@ private static void BuildUnionValueTypeMap(IList<JsonUnionCaseInfo> unionCases,
11761175
}
11771176

11781177
JsonNumberHandling effectiveNumberHandling =
1179-
unionNumberHandling ?? caseTypeInfo.NumberHandling ?? options.NumberHandling;
1178+
caseTypeInfo.NumberHandling ?? options.NumberHandling;
11801179
JsonValueType valueTypes = converter.GetSupportedJsonValueTypes(effectiveNumberHandling);
11811180

11821181
AddUnionValueTypes(valueTypes, caseType, map, ref ambiguousValueTypes);
@@ -1218,41 +1217,6 @@ static void AddUnionValueTypes(
12181217
}
12191218
}
12201219

1221-
internal Type? ResolveUnionCaseType(JsonValueType valueType, JsonNumberHandling? numberHandling, out bool isAmbiguous)
1222-
{
1223-
Type? resolvedCaseType = null;
1224-
1225-
foreach (JsonUnionCaseInfo info in UnionCases)
1226-
{
1227-
Type caseType = info.CaseType;
1228-
JsonTypeInfo caseTypeInfo = Options.GetTypeInfoInternal(caseType);
1229-
JsonConverter converter = caseTypeInfo.Converter;
1230-
if (converter.ConverterStrategy is ConverterStrategy.Union)
1231-
{
1232-
continue;
1233-
}
1234-
1235-
JsonNumberHandling effectiveNumberHandling =
1236-
numberHandling ?? caseTypeInfo.NumberHandling ?? Options.NumberHandling;
1237-
1238-
if ((converter.GetSupportedJsonValueTypes(effectiveNumberHandling) & valueType) == 0)
1239-
{
1240-
continue;
1241-
}
1242-
1243-
if (resolvedCaseType is not null)
1244-
{
1245-
isAmbiguous = true;
1246-
return null;
1247-
}
1248-
1249-
resolvedCaseType = caseType;
1250-
}
1251-
1252-
isAmbiguous = false;
1253-
return resolvedCaseType;
1254-
}
1255-
12561220
/// <summary>
12571221
/// Gets any ancestor polymorphic types that declare
12581222
/// a type discriminator for the current type. Consulted

‎src/libraries/System.Text.Json/tests/Common/UnionTests.cs‎

Lines changed: 39 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -413,14 +413,23 @@ public void UnionWithMixedAmbiguity_GetTypeInfoSucceeds()
413413
Assert.NotNull(typeInfo);
414414
}
415415

416-
[JsonNumberHandling(JsonNumberHandling.Strict)]
417-
public union StrictIntOrString(int, string);
418-
416+
[JsonUnion(TypeClassifier = typeof(IntCaseClassifierFactory))]
419417
[JsonNumberHandling(JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.WriteAsString)]
420-
public union StringEncodedInt(int);
418+
public union NumberHandlingIntUnion(int);
421419

420+
[JsonUnion(TypeClassifier = typeof(IntCaseClassifierFactory))]
422421
public union PlainIntUnion(int);
423422

423+
public sealed class IntCaseClassifierFactory : JsonTypeClassifierFactory
424+
{
425+
public override bool CanClassify(JsonTypeClassifierContext context) =>
426+
context.DeclaringType == typeof(NumberHandlingIntUnion) ||
427+
context.DeclaringType == typeof(PlainIntUnion);
428+
429+
public override JsonTypeClassifier CreateJsonClassifier(JsonTypeClassifierContext context, JsonSerializerOptions options) =>
430+
static (ref Utf8JsonReader reader) => typeof(int);
431+
}
432+
424433
public sealed class UnionNumberHandlingContainer
425434
{
426435
[JsonNumberHandling(JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.WriteAsString)]
@@ -430,27 +439,16 @@ public sealed class UnionNumberHandlingContainer
430439
public sealed class StrictUnionNumberHandlingContainer
431440
{
432441
[JsonNumberHandling(JsonNumberHandling.Strict)]
433-
public MixedUnion Value { get; set; } = new(0);
434-
}
435-
436-
[Fact]
437-
public async Task UnionNumberHandling_TypeAttributeOverridesOptions()
438-
{
439-
JsonSerializerOptions options = Serializer.CreateOptions(
440-
static options => options.NumberHandling = JsonNumberHandling.AllowReadingFromString);
441-
442-
StrictIntOrString? value = await Serializer.DeserializeWrapper<StrictIntOrString>("\"hello\"", options);
443-
444-
Assert.Equal("hello", GetUnionValue(value!));
442+
public PlainIntUnion Value { get; set; }
445443
}
446444

447445
[Fact]
448446
public async Task UnionNumberHandling_TypeAttributeSupportsReadingAndWritingNumbersAsStrings()
449447
{
450-
StringEncodedInt? value = await Serializer.DeserializeWrapper<StringEncodedInt>("\"42\"");
448+
NumberHandlingIntUnion? value = await Serializer.DeserializeWrapper<NumberHandlingIntUnion>("\"42\"");
451449
Assert.Equal(42, GetUnionValue(value!));
452450

453-
string json = await Serializer.SerializeWrapper(new StringEncodedInt(42));
451+
string json = await Serializer.SerializeWrapper(new NumberHandlingIntUnion(42));
454452
Assert.Equal("\"42\"", json);
455453
}
456454

@@ -488,12 +486,31 @@ public async Task UnionNumberHandling_PropertyAttributeSupportsReadingAndWriting
488486
public async Task UnionNumberHandling_StrictPropertyAttributeOverridesOptions()
489487
{
490488
JsonSerializerOptions options = Serializer.CreateOptions(
491-
static options => options.NumberHandling = JsonNumberHandling.AllowReadingFromString);
489+
static options => options.NumberHandling = JsonNumberHandling.WriteAsString);
490+
491+
string json = await Serializer.SerializeWrapper(
492+
new StrictUnionNumberHandlingContainer { Value = new PlainIntUnion(42) },
493+
options);
494+
495+
JsonTestHelper.AssertJsonEqual("""{"Value":42}""", json);
496+
}
497+
498+
[Fact]
499+
public async Task UnionNumberHandling_CaseTypeInfoOverridesOptions()
500+
{
501+
JsonSerializerOptions options = Serializer.CreateOptions(
502+
static options => options.NumberHandling = JsonNumberHandling.WriteAsString,
503+
modifier: static typeInfo =>
504+
{
505+
if (typeInfo.Type == typeof(int))
506+
{
507+
typeInfo.NumberHandling = JsonNumberHandling.Strict;
508+
}
509+
});
492510

493-
StrictUnionNumberHandlingContainer? value =
494-
await Serializer.DeserializeWrapper<StrictUnionNumberHandlingContainer>("""{"Value":"hello"}""", options);
511+
string json = await Serializer.SerializeWrapper(new PlainIntUnion(42), options);
495512

496-
Assert.Equal("hello", GetUnionValue(value!.Value));
513+
Assert.Equal("42", json);
497514
}
498515

499516
public class Animal { }

‎src/libraries/System.Text.Json/tests/System.Text.Json.SourceGeneration.Tests/Serialization/UnionTests.cs‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,7 @@ public UnionTests_Metadata()
3333
[JsonSerializable(typeof(UnionWithCustomConverterCase))]
3434
[JsonSerializable(typeof(UnionWithIntAndLongCase))]
3535
[JsonSerializable(typeof(UnionWithMixedAmbiguity))]
36-
[JsonSerializable(typeof(StrictIntOrString))]
37-
[JsonSerializable(typeof(StringEncodedInt))]
36+
[JsonSerializable(typeof(NumberHandlingIntUnion))]
3837
[JsonSerializable(typeof(PlainIntUnion))]
3938
[JsonSerializable(typeof(UnionNumberHandlingContainer))]
4039
[JsonSerializable(typeof(StrictUnionNumberHandlingContainer))]
@@ -102,8 +101,7 @@ public UnionTests_Default()
102101
[JsonSerializable(typeof(UnionWithCustomConverterCase))]
103102
[JsonSerializable(typeof(UnionWithIntAndLongCase))]
104103
[JsonSerializable(typeof(UnionWithMixedAmbiguity))]
105-
[JsonSerializable(typeof(StrictIntOrString))]
106-
[JsonSerializable(typeof(StringEncodedInt))]
104+
[JsonSerializable(typeof(NumberHandlingIntUnion))]
107105
[JsonSerializable(typeof(PlainIntUnion))]
108106
[JsonSerializable(typeof(UnionNumberHandlingContainer))]
109107
[JsonSerializable(typeof(StrictUnionNumberHandlingContainer))]

0 commit comments

Comments
 (0)