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.
Originally posted by @ilya-scale in #63747 (comment)
This can be reproduced both with
ReferenceHandler.Preserve:and polymorphism
We should validation for both cases to ensure invalid JSON is not emitted over the wire.