Skip to content

JsonNode.DeepEquals method in System.Text.Json returns incorrect value when second object contains item not in first and length is same #114866

@scott-shrout

Description

@scott-shrout

Description

The implementation of JsonObject.DeepEqualsCore is wrong in that it determines 2 objects are equal only if they have the same number of items and the values in the first object are equal to the values in the second object. It doesn't check for non-null values in the second object that aren't in the first.

Object 1:

{
        "item1": null
}

Object 2:

{
         "item2": "test"
}

JsonNode.DeepEquals method returns true when these are clearly not equal.

Reproduction Steps

  1. Create a new console application.
  2. Paste the below code:
using System.Text.Json.Nodes;

var node1 = @" {
        ""item1"": null
}";

var node2 = @" {
        ""item2"": ""test""
}";

var jsonNode1 = JsonNode.Parse(node1);
var jsonNode2 = JsonNode.Parse(node2);

var equal = JsonNode.DeepEquals(jsonNode1, jsonNode2);

Console.WriteLine(equal);
Console.Read();
  1. Observe that result written to console is True.

Expected behavior

JsonObject.DeepEqualsCore returns false if the second object contains a key not in the first object and the value is not null.

Actual behavior

JsonObject.DeepEqualsCore returns true if the second object contains a key not in the first object and the value is not null.

Regression?

No response

Known Workarounds

No response

Configuration

Version: .NET 8.0.15
OS: Microsoft Windows 11
Architecture: x64

Other information

The problem lies in the flawed implementation of JsonObject.DeepEqualsCore.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions