winforms 如何在C#中使用JSON用foreach序列化多个项?

x9ybnkn6  于 2022-11-16  发布在  C#
关注(0)|答案(1)|浏览(147)

我正在尝试序列化2个ListView中的对象,ListView#2用于显示分组的对象,而ListView#2显示上述组。(选择#1中的组将显示#2中的不同对象集)

JsonSerializer serializer = new JsonSerializer();
        using (StreamWriter sw = new StreamWriter(path + "\\data.txt"))
        {
            foreach (ListViewItem group in lV_groups.Items)
            {
                foreach (ListViewItem item in lV_items.Items)
                {
                    List<ItemSerObj> itemsObj = new List<ItemSerObj>()
                    {
                        new ItemSerObj
                        {
                            ItemName = item.SubItems[0].Text,
                            Value = item.SubItems[1].Text,
                            Quality = item.SubItems[2].Text,
                            TimeStamp = item.SubItems[3].Text
                        }
                    };

                    GroupSerObj serializeGroup = new GroupSerObj
                    {
                        GroupName = group.SubItems[0].Text,
                        UpdateRate = group.SubItems[1].Text,
                        Active = group.SubItems[2].Text,
                        Items = itemsObj

                    };

                    using (JsonWriter writer = new JsonTextWriter(sw))
                    {
                        serializer.Serialize(writer, serializeGroup); //Where exception occurs.
                    }
                }
            }
        }

出现“系统.对象处理异常:“无法写入已关闭的TextWriter”“异常。

clj7thdc

clj7thdc1#

只需将其更改为如下形式:

JsonSerializer serializer = new JsonSerializer();
using (StreamWriter sw = new StreamWriter(path + "\\data.txt"))
{
    using (JsonWriter writer = new JsonTextWriter(sw))
    {
        foreach (ListViewItem group in lV_groups.Items)
        {
            List<ItemSerObj> itemsObj = new List<ItemSerObj>();

            foreach (ListViewItem item in lV_items.Items)
            {
                itemsObj.Add(
                new ItemSerObj
                {
                    ItemName = item.SubItems[0].Text,
                    Value = item.SubItems[1].Text,
                    Quality = item.SubItems[2].Text,
                    TimeStamp = item.SubItems[3].Text
                });           
            }

            GroupSerObj serializeGroup = new GroupSerObj
            {
                GroupName = group.SubItems[0].Text,
                UpdateRate = group.SubItems[1].Text,
                Active = group.SubItems[2].Text,
                Items = itemsObj
            };

            serializer.Serialize(writer, serializeGroup);
        }
    }
}

每个组迭代都会创建一个新List,此List将填充到foreach循环内部
之后,将其添加到GroupSerObj并进行序列化

相关问题