Fix PolymorphicObjectConverter handling of primitive values (#7207)
* Fix PolymorphicObjectConverter handling of primitive values * Add integration test for polymorphic serialization of primitive values --------- Co-authored-by: Vedika Gupta <vedikagupta@Vedikas-MacBook-Pro.local>
This commit is contained in:
parent
dfa94e4295
commit
55bacd8b20
|
|
@ -242,6 +242,15 @@ public class PolymorphicObjectConverter : JsonConverter<object>
|
|||
return;
|
||||
}
|
||||
|
||||
// If the value was serialized as a primitive by another converter,
|
||||
// write it directly instead of assuming an object structure.
|
||||
if (jsonElement.ValueKind != JsonValueKind.Object &&
|
||||
jsonElement.ValueKind != JsonValueKind.Array)
|
||||
{
|
||||
jsonElement.WriteTo(writer);
|
||||
return;
|
||||
}
|
||||
|
||||
writer.WriteStartObject();
|
||||
|
||||
if (jsonElement.ValueKind == JsonValueKind.Array)
|
||||
|
|
|
|||
|
|
@ -87,4 +87,30 @@ public class Tests
|
|||
options.Converters.Add(new PolymorphicObjectConverterFactory(new WellKnownTypeRegistry()));
|
||||
return options;
|
||||
}
|
||||
|
||||
[Fact(DisplayName = "Types with custom converters that serialize to primitives are serialized as primitives")]
|
||||
|
||||
public void CustomConverterProducingPrimitive_IsSerializedAsPrimitive()
|
||||
{
|
||||
var model = new MyNumber { Number = 123UL };
|
||||
var options = GetSerializerOptions();
|
||||
var expectedJson = "123";
|
||||
var json = JsonSerializer.Serialize<object>(model, options);
|
||||
Assert.Equal(expectedJson, json);
|
||||
}
|
||||
|
||||
[JsonConverter(typeof(MyNumberConverter))]
|
||||
private struct MyNumber
|
||||
{
|
||||
public ulong Number { get; init; }
|
||||
}
|
||||
|
||||
private class MyNumberConverter : JsonConverter<MyNumber>
|
||||
{
|
||||
public override MyNumber Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
=> new() { Number = reader.GetUInt64() };
|
||||
|
||||
public override void Write(Utf8JsonWriter writer, MyNumber value, JsonSerializerOptions options)
|
||||
=> writer.WriteNumberValue(value.Number);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue