Search code examples
c#json.net

C# Remove Square Brackets From Array


I am building a Web API and am working account to the exact requirements set out by the external company who will be retrieving the data from the API via a GET request. One requirement is to have square brackets enclosing arrays within the return to be removed. Below is an example of what I currently have - the Departments of Religions, Languages and History are enclosed in square brackets;

{
    "roles": [
        [
            "STUDENT",
            "Undergraduate",
            3,
            [
                "History",
                "Languages",
                "Religions"
            ],
            "GIBSON, David Test",
            666778
        ]
    ]
}

What they require is for the return to look like this;

{
  "roles": [
    [
      "STUDENT",
      "Undergraduate",
      3,
      "History",
      "Languages",
      "Religions",
      "GIBSON, David Test",
      666778
    ]
  ]
}

Not sure if this will help, but the three Departments above are an array called deptarray i.e. if a student belongs to more than one department, list those departments in the return as an array;

var deptarray = jArr.Distinct();

if (deptarray.Count() > 1) studentList[0][i] = new JArray(deptarray);

I would be grateful for any help in removing the square bracket enclosures and just having the departments in double quotes.


Solution

  • I see you never stop. This is your code that you have to add to your ADO.net

       var roles = JArray.From(studentRoles);
    
        if (roles.Count() > 1)
        {   
             var newArr = new JArray();
            for (int j = 0; j < roles[0].Count(); j++)
            {
                var jArr = new JArray();
                for (var i = 1; i < roles.Count(); i++)
                {
                    if (i == 1) jArr = new JArray { roles[0][j] };
                    jArr.Add(roles[i][j]);
                }
     
                var arr = jArr.Distinct();
    
                if (arr.Count() > 1)
                    foreach (var item in arr)
                    {
                        newArr.Add(item);
                    }
                else newArr.Add(arr.First());
                    
                }
           }
             roles=newArr;
         }
    
    var response = Request.CreateResponse(HttpStatusCode.OK, new { roles = roles 
    });