0

I am using System.Text.Json

My sample json is

{
    "a": {}
}

I am reading key "a" from json and converting JsonNode to JsonObject.

JsonObject jsonObject = jsonForTest.AsObject();
JsonArray array = new JsonArray();                
array.Add(jsonForTest);

When I do array.add() It gives an exception

System.InvalidOperationException: The node already has a parent.

--- Stack Trace: 
ThrowHelper.ThrowInvalidOperationException_NodeAlreadyHasParent()
JsonNode.AssignParent(JsonNode parent)
JsonArray.Add(JsonNode item)

I have tried to add the object to array but it doesn't work. It should work as in Newtonsoft.Json to add the object to array.

Ankur
  • 21
  • 5
  • 1
    Your question doesn't include a [mcve], but it seems that `jsonForTest` must already belong to some parent `JsonObject` or `JsonArray`. If so, you must remove it from the parent first before you add it to the new parent. Alternatively, you must copy it. See [Clone a JsonNode and attach it to another one in .NET 6](https://stackoverflow.com/q/71570877/3744182) which looks to be a duplicate; the `CopyNode()` and `MoveNode()` extension methods from [this answer](https://stackoverflow.com/a/71590703/3744182) should do what you need. – dbc Apr 04 '22 at 21:51
  • BTW, Newtonsoft actually clones a `JToken` that already has a parent when you add it to a different parent, see e.g. [nested json objects dont update / inherit using Json.NET](https://stackoverflow.com/a/29260565). – dbc Apr 04 '22 at 21:55
  • @dbc I have added the sample json thats needed for reproduction. I am reading json from a file and using it to process the json object that in input from the file. – Ankur Apr 04 '22 at 22:20
  • *I am reading key "a" from json and converting JsonNode to JsonObject... When I do `array.add()` It gives an exception* - right, so as stated in the duplicate you need to remove `"a"` from the parent before adding it to the array, using [`JsonObject.Remove("a")`](https://learn.microsoft.com/en-us/dotnet/api/system.json.jsonobject.remove). Alternatively you need to clone the value of `a` with the extension method shown in the duplicate. Are you still confused? What is the difficulty? – dbc Apr 04 '22 at 22:22

0 Answers0