Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    {
      "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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading