如何组合对象以便同时显示所有对象作为JSON

本文关键字:对象 显示 JSON 何组合 组合 | 更新日期: 2023-09-27 18:25:18

在下面的代码中,检查以下行:

//here I need to put the object "nd" into a "bucket" so that I can finish the loop and then return EVERYTHING together.

我的问题是,如何组合对象以JSON形式返回?我之所以需要"组合",是因为循环为这个类的特定属性赋值。一旦每个类都完成了属性值的获取,我就需要将所有内容作为JSON返回。

namespace X
{
    public class NotificationsController : ApiController
    {
        public List<NotificationTreeNode> getNotifications(int id)
        {
            var bo = new HomeBO();
            var list = bo.GetNotificationsForUser(id);
            var notificationTreeNodes = (from GBLNotifications n in list
                                        where n.NotificationCount != 0
                                        select new NotificationTreeNode(n)).ToList();
            foreach (var notificationTreeNode in notificationTreeNodes)
            {
                Node nd = new Node();
                nd.notificationType = notificationTreeNode.NotificationNode.NotificationType;
                var notificationList = bo.GetNotificationsForUser(id, notificationTreeNode.NotificationNode.NotificationTypeId).Cast<GBLNotifications>().ToList();
                List<string> notificationDescriptions = new List<string>();
                foreach (var item in notificationList)
                {
                    notificationDescriptions.Add(item.NotificationDescription);
                }
                nd.notifications = notificationDescriptions;
                //here I need to put the object "nd" into a "bucket" so that I can finish the loop and then return EVERYTHING together.
            }
            return bucket;
        }
    }
    public class Node
    {
        public string notificationType
        {
            get;
            set;
        }
        public List<string> notifications
        {
            get;
            set;
        }
    }
}

如何组合对象以便同时显示所有对象作为JSON

您可以在迭代源集合时简单地将每个项目添加到列表中:

public List<Node> getNotifications(int id)
{
    var bucket = new List<Node>(notificationTreeNodes.Count);
    foreach (var notificationTreeNode in notificationTreeNodes)
    {
        Node nd = new Node();
        ...
        bucket.Add(nd);
    }
    return bucket;
}