简体   繁体   中英

How to create a Json array in C# MVC Controller

I have an List of Doors that looks like :

DoorId   DoorName  ControllerId ControllerName
------   --------  ------------ --------------

Door1    DoorOne   C1           C1
Door2    DoorTwo   C1           C1
Door3    DoorThree C2           C2

I need to format it like this :

            var doorsForSite = new[]
                {
                new { ControllerId ="C1",ControllerName="C1",IsChecked = "false",
                        Doors = new[]
                        {
                            new { DoorId="Door1",DoorName="DoorOne",Schedules = scheduleList},
                            new { DoorId="Door2",DoorName="DoorTwo",Schedules = scheduleList},
                        }

                    },
                new { ControllerId ="C2",ControllerName="C2",IsChecked = "false",
                        Doors = new[]
                        {
                            new { DoorId=  "Door3",DoorName="DoorThree",Schedules = scheduleList}
                        }

                    }
            };

That is group by ControllerId and ControllerName and then build the Doors array .

How to do it ?

Install JSON.net nuget package. Use JsonConvert.SerializeObject function

string jsonArray = JsonConvert.SerializeObject(doorsForSite);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM