Skip to content

System.Text.Json metadata writer does not check for property name conflicts #72170

Description

@eiriktsarpalis

Originally posted by @ilya-scale in #63747 (comment)

This can be reproduced both with ReferenceHandler.Preserve:

var value = new Poco { Value = "string" };
var options = new JsonSerializerOptions { ReferenceHandler = ReferenceHandler.Preserve };
string json = 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. 

public class Poco
{
    [JsonPropertyName("$id")]
    public string Value { get; set; }
}

and polymorphism

Base value = new Derived { Value = "value" };
string json = JsonSerializer.Serialize(value);
Console.WriteLine(json); // {"$type":"derived","$type":"value"}
Base result = JsonSerializer.Deserialize<Base>(json); // System.Text.Json.JsonException: 'Deserialized object contains a duplicate type discriminator metadata property. 
Console.WriteLine(result is Derived);

[JsonDerivedType(typeof(Base), "base")]
[JsonDerivedType(typeof(Derived), "derived")]
public class Base
{
    [JsonPropertyName("$type")]
    public string Value { get; set; }
}

public class Derived : Base
{
}

We should validation for both cases to ensure invalid JSON is not emitted over the wire.

Metadata

Metadata

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions