How to make nested json from json string

2020-05-09 22:19发布

问题:

I am tring to create nested json string here is my json string below,

[  
   {  
      'CompanyID':'1',
      'Name':'Company1',
      'DepartmentName':'Executive General and Administration',
      'ModifiedDate':'2005-06-01 00:00:00.000',

   },
   {  
      'CompanyID':'2',
      'Name':'Company2',
      'DepartmentName':'Executive General and Administration',
      'ModifiedDate':'2005-06-01 00:00:00.000',

   },
   {  
      'CompanyID':'3',
      'Name':'Company3',
      'DepartmentName':'Executive General and Administration',
      'ModifiedDate':'2005-06-01 00:00:00.000',

   }
]

and i want result like this

[  
   {  
      'CompanyID':'1',
      'Name':'Company1',
       department":{
            'DepartmentName': 'Dpt1'
       }
    }
]

I want company wise department for this json string... I used Jarray but failed to do so...

my code:

string jsonCompany = "[{'CompanyID' : '1','Name' : 'Company1','DepartmentName' : 'D1','ModifiedDate' : '2005-06-01 00:00:00.000',},{'CompanyID' : '2','Name' : 'Company2','DepartmentName' : 'D2','ModifiedDate' : '2005-06-01 00:00:00.000',},{'CompanyID' : '1','Name' : 'Company3','DepartmentName' : 'D3','ModifiedDate' : '2005-06-01 00:00:00.000',}]";

string jsonDept = "[{'DepartmentID' : '91','Name' : 'Executive84','GroupName' : 'Executive General and Administration','ModifiedDate' : '2005-06-01 00:00:00.000',},{'DepartmentID' : '92','Name' : 'Executive85','GroupName' : 'Executive General and Administration','ModifiedDate' : '2005-06-01 00:00:00.000',},{'DepartmentID' : '93','Name' : 'Executive86','GroupName' : 'Executive General and Administration','ModifiedDate' : '2005-06-01 00:00:00.000',}]";

object dynJsonCmp = JsonConvert.DeserializeObject(jsonCompany);

dynamic dynJsonDept = JsonConvert.DeserializeObject(jsonDept);

回答1:

One of the cleanest ways of such manipulation is with using classes. Based on the json you initially provided, and your initial question, you can do the following.:

class Company
{

    public int CompanyID { get; set; }
    public string Name { get; set; }
    public string DepartmentName { get; set; }

    public object Modify => new {
        CompanyID, Name, department = new { DepartmentName }
    };

}

Then you can simply deserialize into a list, convert it with the help of Linq and serialize it

var modifiedList = JsonConvert.DeserializeObject<List<Company>>(jsonCompany).Select(c => c.Modify);
string updatedJson = JsonConvert.SerializeObject(modifiedList);

Since your code seems to show a different json, you may have to modify the Linq part according to what you are actually trying to do. You can look into Linq to check what exactly you are trying to do.