You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
System.Text.Json metadata writer does not check for property name conflicts #72170
This can be reproduced both with ReferenceHandler.Preserve:
varvalue=newPoco{Value="string"};varoptions=newJsonSerializerOptions{ReferenceHandler=ReferenceHandler.Preserve};stringjson=JsonSerializer.Serialize(value,options);Console.WriteLine(json);// {"$id":"1","$id":"string"}JsonSerializer.Deserialize<Poco>(json,options);// Fails with 'The metadata property '$id' must be the first reference preservation property in the JSON object. publicclassPoco{[JsonPropertyName("$id")]publicstringValue{get;set;}}
and polymorphism
Basevalue=newDerived{Value="value"};stringjson=JsonSerializer.Serialize(value);Console.WriteLine(json);// {"$type":"derived","$type":"value"}Baseresult=JsonSerializer.Deserialize<Base>(json);// System.Text.Json.JsonException: 'Deserialized object contains a duplicate type discriminator metadata property. Console.WriteLine(resultisDerived);[JsonDerivedType(typeof(Base),"base")][JsonDerivedType(typeof(Derived),"derived")]publicclassBase{[JsonPropertyName("$type")]publicstringValue{get;set;}}publicclassDerived:Base{}
We should validation for both cases to ensure invalid JSON is not emitted over the wire.
Reacted by Wojciech Nagórski, Zdeněk Jelínek, Trivivium and Евгений Ишутин
Would there be a way to have both polymorphic deserialization and a possibility to read the property, i.e. the discriminator from the resulting C# object, or you want to explicitly prohibit it so that it will not be possible?
It is probably not a bad idea though to allow reading the type discriminator unless it will lead to some unforeseen consequences or complicated implementation?
When I created this issue, I had assumed that this would be a metadata validation concern, but this is not the case with dictionary types; we'd need to validate individual key/value pairs at runtime which is not ideal from a performance perspective, and may not even be possible if we have a converter that overrides WriteAsPropertyName.
If not possible to enforce on Dictionary types, does it make sense to enforce it on object types from a consistency perspective?
Moving to Future, we can consider doing this in later releases should there be demand.
Related issue: #1780. That one suggests escaping $ to avoid conflicts, however polymorphism makes it possible to define metadata properties with $ prefixes.
I think the problem primarily here is with serialization: it emits duplicate entries even though these are impossible to deserialize using the same configuration. That being said, it's not a particularly important problem.
I have a related problem where I can avoid duplicate serialization, however I wasn't able to get the Type object property (also used as the discriminator) populated on deserialization.
@dennis-yemelyanov the scenario you're describing is not supported. Type discriminators map string identifiers to specific derived types and as such they cannot be bound to the runtime value of any properties of the object being serialized.
Thank you @eiriktsarpalis for confirming. I came up with a slightly different approach using a converter, but was curious if this approach is safe or could have potential issues like infinite recursion due to passing the same options to Serialize/Deserialize?
Basically in the converter for the base class I first read json as JsonObject, then convert it to a specific class depending on the Type value. And when writing the JSON, simply write the object as a specific class:
classPolymorphicConverter:JsonConverter<Base>{publicoverrideBase?Read(refUtf8JsonReaderreader,TypetypeToConvert,JsonSerializerOptionsoptions){varjsonObj=JsonSerializer.Deserialize<JsonObject>(refreader,options);vartype=(string)jsonObj["Type"];returntypeswitch{"Person"=>jsonObj.Deserialize<Person>(options),
_ =>thrownewInvalidOperationException($"Unknown type '{type}'")};}publicoverridevoidWrite(Utf8JsonWriterwriter,Basevalue,JsonSerializerOptionsoptions){if(valueisPersonperson){JsonSerializer.Serialize(writer,person,options);}else{thrownewInvalidOperationException($"Unknown type '{value.GetType().Name}'");}}}
This also requires configuring a modifier for the Type property so it can have the correct value depending on the actual class type:
this is issue for me, because when I serialize object which has 2 same properties (one injected by poly features of STJ and second just being there for a convenience on a server side) like so
I have issue like #91274 which was closed as a duplicate of this one.
I use JsonPolymorphic with UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType and want to know what was value of Discriminator for "Unknown" type, but it seems impossible right now. Example
Activity
ilya-scale commentedon Jul 14, 2022
Would there be a way to have both polymorphic deserialization and a possibility to read the property, i.e. the discriminator from the resulting C# object, or you want to explicitly prohibit it so that it will not be possible?
eiriktsarpalis commentedon Jul 14, 2022
I think it would make sense to explicitly prohibit.
ilya-scale commentedon Jul 15, 2022
It is probably not a bad idea though to allow reading the type discriminator unless it will lead to some unforeseen consequences or complicated implementation?
eiriktsarpalis commentedon Aug 2, 2022
When I created this issue, I had assumed that this would be a metadata validation concern, but this is not the case with dictionary types; we'd need to validate individual key/value pairs at runtime which is not ideal from a performance perspective, and may not even be possible if we have a converter that overrides
WriteAsPropertyName.If not possible to enforce on Dictionary types, does it make sense to enforce it on object types from a consistency perspective?
Moving to Future, we can consider doing this in later releases should there be demand.
eiriktsarpalis commentedon Aug 4, 2022
Related issue: #1780. That one suggests escaping
$to avoid conflicts, however polymorphism makes it possible to define metadata properties with$prefixes.1 remaining item
eiriktsarpalis commentedon Dec 2, 2022
I think the problem primarily here is with serialization: it emits duplicate entries even though these are impossible to deserialize using the same configuration. That being said, it's not a particularly important problem.
dennis-yemelyanov commentedon Feb 22, 2023
I have a related problem where I can avoid duplicate serialization, however I wasn't able to get the
Typeobject property (also used as the discriminator) populated on deserialization.For example, for the following class hierarchy:
I wrote the following TypeResolver with an option to remove the
Typeproperty and avoid duplicate "Type" json keys written on serialization:I use the following code to create and roundtrip an object:
The problem is that the last line doesn't optput correct
Typevalue:I want it to print
Type: Person; Name Johninstead.I would appreciate it if there are any workarounds, maybe some customer converters or other tricks can be used to achieve the desired result?
eiriktsarpalis commentedon Feb 22, 2023
@dennis-yemelyanov the scenario you're describing is not supported. Type discriminators map string identifiers to specific derived types and as such they cannot be bound to the runtime value of any properties of the object being serialized.
dennis-yemelyanov commentedon Feb 22, 2023
Thank you @eiriktsarpalis for confirming. I came up with a slightly different approach using a converter, but was curious if this approach is safe or could have potential issues like infinite recursion due to passing the same
optionstoSerialize/Deserialize?Basically in the converter for the base class I first read json as
JsonObject, then convert it to a specific class depending on theTypevalue. And when writing the JSON, simply write the object as a specific class:This also requires configuring a modifier for the
Typeproperty so it can have the correct value depending on the actual class type:This seems to work and prints the expected result:
Would you recommend going with this approach or are there any potential risks that I missed?
vmachacek commentedon Feb 25, 2025
this is issue for me, because when I serialize object which has 2 same properties (one injected by poly features of STJ and second just being there for a convenience on a server side) like so
than on deserialization it fails because it wont like the fact the
TypeDiscriminatorPropertyis duplicated .Any work around that?
Rick-van-Dam commentedon Mar 31, 2025
Running into this as well. Will this be fixed in .NET 10 since it was added to that milestone?
WojciechNagorski commentedon Apr 23, 2025
@Rick-van-Dam here you have a workaround #110248 (comment)
mnovikov-mindbox commentedon Jan 20, 2026
I have issue like #91274 which was closed as a duplicate of this one.
I use
JsonPolymorphicwithUnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseTypeand want to know what was value of Discriminator for "Unknown" type, but it seems impossible right now. Example"Type" property never get filled by deserializer.