Add new node in exisgintg json at top .NET

I have following json and I want to add new node in that like below.

I am working .NET Core API, I am thinking to add new node using Jobject but still not get clear idea on that part.. I am using System.Text.Json to Serialize data..

My current json looks like this:

    {
      "Test1": {
        "2020": [
          "40%",
          "40%",
          "40%",
          "40%"
        ],
        "2021": [
          "50%",
          "30%",
          "30%",
          "40%"
        ]
      },
      "Test2": {
        "2020": [
          "No",
          "No",
          "No",
          "No"
        ],
        "2021": [
          "No",
          "No",
          "No",
          "No"
        ]
}
}

Now I want to add new node in top before Test1, so new json should look like this.

{
  "Newnode": {
    "Test1": {
      "2020": [
        "40%",
        "40%",
        "40%",
        "40%"
      ],
      "2021": [
        "50%",
        "30%",
        "30%",
        "40%"
      ]
    },
    "Test2": {
      "2020": [
        "No",
        "No",
        "No",
        "No"
      ],
      "2021": [
        "No",
        "No",
        "No",
        "No"
      ]
    }
  }
}

>Solution :

There are multiple options to work with JSON DOM using System.Text.Json. Since .NET 6 for example you can use the JsonNode API:

var jsonNode = JsonNode.Parse(jsonStr);
var jsonObject = new JsonObject();
jsonObject["Newnode"] = jsonNode;
var result = jsonObject.ToJsonString();

Leave a Reply