获取具有相同键的项目已添加映射模型时出错

问题描述

"Types": [
            {
                "activeFlag": true,"Type": "Out"
            },{
                "activeFlag": true,"Type": "Today"
            },"Type": "Later"
            },"Type": "Now"
            },"Type": "Example"
            },"Type": "Hour"
            },"Type": "In"
            }
        ],

我在json结构上方有一个尝试将其映射到我的模型中,因此它具有多个activeFlag属性

public class Info
{
    public Dictionary<string,string> Types { get; set; }

}


...Types = new Dictionary<string,string>
                    {
                        { "activeFlag","true" },{ "Type","Out" },{ "activeFlag","Today" },"Later" },"Now" }...
                    }...

以下代码给出了An item with the same key has already been added ,我该如何正确映射?

解决方法

在字典中,键值必须唯一,您要多次添加activeFlag。一种更好的方法是使用一个包含所需属性的类。例如:

public class Item
{
    public bool ActiveFlag { get; set; }
    public string Type { get; set; }
}

并使您的基础对象成为此类的列表:

public class Info
{
    public List<Item> Types { get; set; }
}

现在您可以正确地反序列化了。

,

字典的键必须是唯一的,您可以使用这样的元组 List<Tuple<string,string>>或此List<(string,string)>