diff --git a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.cs b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.cs index 20cdc076aac64..e310382c1f3f5 100644 --- a/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.cs +++ b/src/libraries/System.Text.Json/src/System/Text/Json/Nodes/JsonObject.cs @@ -248,17 +248,21 @@ internal void SetItem(string propertyName, JsonNode? value) OrderedDictionary dict = Dictionary; - if (dict.TryGetValue(propertyName, out JsonNode? replacedValue)) + if (!dict.TryAdd(propertyName, value)) { + int index = dict.IndexOf(propertyName); + Debug.Assert(index >= 0); + JsonNode? replacedValue = dict.GetAt(index).Value; + if (ReferenceEquals(value, replacedValue)) { return; } DetachParent(replacedValue); + dict.SetAt(index, value); } - dict[propertyName] = value; value?.AssignParent(this); }