Home > Back-end >  Adding root node to json structure
Adding root node to json structure

Time:02-19

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": " ",
  } }}]}

CodePudding user response:

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

  • Related