StrugglingCoder StrugglingCoder - 1 month ago 15
C# Question

Nested Json array in MVC Controller

Pretty silly question to ask. but could not figure it out .

In a C# MVC Controller action , I need to model a Json Array for testing purposes.

But this shows me compilation errors instead of being a valid Json:

var result = {
"controllerId": "controller1",
"controllerName": "ControllerOne"
};


But this is perfectly valid :

var scheduleResult = new[]
{
new { scheduleId = "schedule1",scheduleName = "scheduleOne"},
new { scheduleId = "schedule2",scheduleName = "scheduleTwo"}
};


Why so ?

Also how to write a nested Json array :

I tried :

var scheduleResult = new[]
{
new { scheduleId = "schedule1",scheduleName = "scheduleOne",new[]{ new {doorId="Door1",doorName="DoorOne"}, new { doorId = "Door2", doorName = "DoorTwo" } } },
new { scheduleId = "schedule2",scheduleName = "scheduleTwo"}
};


But it shows errors in syntax. What to do ?

I Need to have nested array within each element of that array .

Thanks in advance.

Answer

Well, C# does not support the way you wrote. You can't just type in JSON in C# and expect it to work unfortunately. You can try like that with anonymous type:

 var result = new 
 {
     controllerId = "controller1",
     controllerName = "ControllerOne",
     myArray = new [] 
     {
          "a",
          "b"
     }
 };

This is converted to JSON no problem if you return it as a result of API call.

The nested arrays you are talking about don't work because you need to give them a name, you can't have array property without a name. See example above.