StrugglingCoder
StrugglingCoder

Reputation: 5021

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.

Upvotes: 1

Views: 1757

Answers (3)

Ninshid
Ninshid

Reputation: 58

Here first of all we should create model class with the same pattern of our return type

 public class ScheduleModel
    {
        public List<Schedule> ScheduleList { get; set; }
    }

    public class Schedule
    {
        public int ScheduleId { get; set; }
        public string ScheduleName { get; set; }
        public List<Door> DoorList { get; set; }
    }

    public class Door
    {
        public int DoorId { get; set; }
        public string DoorName { get; set; }
    }

Now at the controller Action create the test data

List<Door> doorList = new List<Door>();
            doorList.Add(new Door{DoorId = "Door1",DoorName = "DoorOne"});
            doorList.Add(new Door{DoorId = "Door2",DoorName = "DoorTwo"});

            List<Schedule> scheduleList = new List<Schedule>();
            scheduleList.Add(new Schedule{
                ScheduleId = "schedule1",
                ScheduleName = "scheduleOne",
                DoorList = doorList
            });

            scheduleList.Add(new Schedule
            {
                ScheduleId = "schedule2",
                ScheduleName = "scheduleTwo",
            });

            return Json(scheduleList, JsonRequestBehavior.AllowGet);

If this answer benefits you please mark as an answer.

Upvotes: 0

T&#226;n
T&#226;n

Reputation: 1

Why don't you use Dictionary<TKey, TValue> with Newtonsoft.Json?

Simple json:

IDictionary<string, string> obj = new Dictionary<string, string>();
obj.Add("controllerId", "controller1");
obj.Add("controllerName", "ControllerOne");

// {"controllerId":"controller1","controllerName":"ControllerOne"}
string json = JsonConvert.SerializeObject(obj);

Nested json:

IList<string> obj = new List<string>();

IDictionary<string, string> first = new Dictionary<string, string>();
first.Add("scheduleId ", "schedule1");
first.Add("scheduleName", "scheduleOne");

IDictionary<string, string> second = new Dictionary<string, string>();
second.Add("scheduleId ", "schedule2");
second.Add("scheduleName", "scheduleTwo");

string first_json = JsonConvert.SerializeObject(first);
string second_json = JsonConvert.SerializeObject(second);

obj.Add(first_json);
obj.Add(second_json);

// ["{\"scheduleId \":\"schedule1\",\"scheduleName\":\"scheduleOne\"}","{\"scheduleId \":\"schedule2\",\"scheduleName\":\"scheduleTwo\"}"]
string json = JsonConvert.SerializeObject(obj);

Upvotes: 0

Ilya Chernomordik
Ilya Chernomordik

Reputation: 30185

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.

Upvotes: 1

Related Questions