Home > Net >  Moving all properties from a nested JObject to the root
Moving all properties from a nested JObject to the root

Time:09-21

I have the following json format that I need to change by removing the "root" element and then sending it for processing.

{
   "deonItemDetails":[
      {
         "hsDesc":"",
         "namePLU":"AGO LOCAL",
         "taxRate":0.0,
         "unitPrice":71.0,
         "discount":0.0,
         "hsCode":"",
         "quantity":1.0,
         "measureUnit":"Litres",
         "vatClass":"A"
      }
   ],
   "root":{
      "senderId":"a4031de9-d11f-4b52-8cca-e1c7422f3c37",
      "invoiceCategory":"tax_invoice",
      "traderSystemInvoiceNumber":"34058",
      "relevantInvoiceNumber":"",
      "pinOfBuyer":"P051400323I",
      "invoiceType":"Original",
      "exemptionNumber":"",
      "totalInvoiceAmount":71.0,
      "systemUser":"manager"
   }
}

I need it to be like this:

{
   "deonItemDetails":[
      {
         "hsDesc":"",
         "namePLU":"AGO LOCAL",
         "taxRate":0.0,
         "unitPrice":71.0,
         "discount":0.0,
         "hsCode":"",
         "quantity":1.0,
         "measureUnit":"Litres",
         "vatClass":"A"
      }
   ],   
   "senderId":"a4031de9-d11f-4b52-8cca-e1c7422f3c37",
   "invoiceCategory":"tax_invoice",
   "traderSystemInvoiceNumber":"34058",
   "relevantInvoiceNumber":"",
   "pinOfBuyer":"P051400323I",
   "invoiceType":"Original",
   "exemptionNumber":"",
   "totalInvoiceAmount":71.0,
   "systemUser":"manager"   
}

However, using the following code, all content of root is removed instead of just the tag and brackets belinging to that node.

JObject jo = JObject.Parse(jsonToSendDetails);

jo.Property("root").Remove();
var newjson = jo.ToString();

How do I get the json to look like the 2nd one?

CodePudding user response:

Solution 1

@JonSkeet had explained the concept:

  1. Get the properties in the root.
  2. Add the properties from 1 to the JObject.
  3. Remove the root property from the JObject.

The below code is the implementation:

using Newtonsoft.Json.Linq;

JObject jObj = JObject.Parse(json);
JObject rootObj = (JObject)jObj["root"];
        
foreach (JProperty prop in rootObj.Properties())
{
    jObj.Add(prop.Name, prop.Value);
}
        
jObj.Remove("root");

Demo Solution 1 @ .Net Fiddle


Solution 2

Besides, you may work with JObject.Merge() as well.

using Newtonsoft.Json.Linq;

JObject jObj = JObject.Parse(json);     
jObj.Merge(jObj["root"]);
jObj.Remove("root");

Demo Solution 2 @ .NET Fiddle

CodePudding user response:

just for the record

var jsonParsed = JObject.Parse(json);

var fixedObj = (JObject)jsonParsed["root"];

//if, most probably, the order of properties doesn't matter
fixedObj["deonItemDetails"] = jsonParsed["deonItemDetails"];

json = fixedObj.ToString();


// or if the order of properties matters
fixedObj.Properties().First()
  .AddBeforeSelf( new JProperty("deonItemDetails", jsonParsed["deonItemDetails"]) );
  • Related