Skip to content

Preserved references should avoid calling object converter #1776

@jozkee

Description

@jozkee

As of now, if the JSON object that is passed to the internal converter for an object type is a reference { "$ref": "#" } we create a JsonElement for such object/property.

Instead we could search into the map of references and take the value from there.

Repro:

private class Node
{
    public Node Child { get; set; }
    public object Sibling { get; set; }
}

[Fact]
public static void PreserveReferenceOnTypesWithObjectConverter()
{
    Node root = new Node();
    root.Child = new Node();
    root.Sibling = root.Child;
    // Ok.
    Assert.Same(root.Child, root.Sibling);

    JsonSerializerOptions opts = new JsonSerializerOptions
    {
        ReferenceHandling = ReferenceHandling.Preserve
    };

    string json = JsonSerializer.Serialize(root, opts);
    /* serialized object:
    {
        "$id": "1",
        "Child": {
            "$id": "2"
        },
        "Sibling": {
            "$ref": "2"
        }
    }
    */

    Node rootCopy = JsonSerializer.Deserialize<Node>(json, opts);
    // Fails, rootCopy.Sibling is a JsonElement.
    Assert.Same(rootCopy.Child, rootCopy.Sibling);
}

cc @ahsonkhan, @steveharter, @layomia

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions