[SOLVED] Adding root node to json structure

Issue

I have below json structure. I need to add extra tag element documents as a list to entire my json structure. Please advise how can I achieve this.

{
  "issuer": {
    "address": {
      "branchID": " ",
      "country": " ",
      "governate": " "
    }
  }
}

Expecting below Output:

{
  "documents": [
    {
      "issuer": {
        "address": {
          "branchID": " ",
          "country": " ",
          "governate": " "
        }
      }
    }
  ]
}

Solution

Not the most proper way to do it tbh (hacky solution) but if you have access to the input you can modify your input before serializing to json.

var inputJson = "{\"issuer\":{\"address\":{\"branchID\":\"\",\"country\":\"\",\"governate\":\"\"}}}";
var stringifiedJson = "{\"documents\": [" + inputJson + "]}";   
Console.WriteLine(JsonSerializer.Serialize<dynamic>(stringifiedJson, new JsonSerializerOptions() {WriteIndented = true}));

dotnet fiddle: https://dotnetfiddle.net/mdM7ln

Assumptions:

  1. You recieve this json as an input. If you are the one creating it then make a list documents and serialize that instead.
  2. I assumed you are using System.Text.Json but the above should work with any serializer.

ps: Check System.Text.Json.JsonSerializer.Serialize adds \u0022 for the u0022 if needed

Answered By – Convel

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *