Search code examples
c#jsonjson.net

Json converting json array object to json object


I have json with below structure. I want to remove the array and make that a object as there will be only one element in that array. What is the best way to do this. I don't want to hardcode any node other than students and student node in the code

Input JSON

{
  "students": {
    "a": "qw",
    "b": "er",
    "student": [
      {
        "Id": "1",
        "details": {
         
          "q": "12",
          "w": "wer",
          "e": "rty",
          "r": "yui"
        }
      }
    ]
  }
}

Output JSON

{
  "students": {
    "a": "qw",
    "b": "er",
    "student": {
      "Id": "1",
      "details": {
        "q": "12",
        "w": "wer",
        "e": "rty",
        "r": "yui"
      }
    }
  }
}

Solution

  • you can try this

        using Newtonsoft.Json;
    
        var jObj = JObject.Parse(json);
    
        jObj["students"]["student"] = jObj["students"]["student"][0];
    
        json = jObj.ToString();