使用 ExpandoObject 和 IDictionary 创建 JSON 时允许同一个键有多个值

Allow multiple values for the same key when creating JSON using ExpandoObject and IDictionary

我正在尝试使用 ExpandoObject 和 IDictionary 创建动态 JSON。

在 JSON 的动态创建过程中,可能会出现名称或值重复的情况。但是,将重复的名称或值添加到 ExpandoObject 时,会报错:

An item with the same key has already been added.

下面是我的代码片段:

DataTable dt_MappedColumns = (DataTable)ViewState["MappedColumns"];
dynamic ManCols = new ExpandoObject();
var dictionary1 = (IDictionary<string, object>)ManCols;
foreach (DataRow dr in dt_MappedColumns.Rows)
{
     dictionary1.Add(dr["TColumnName"].ToString(), dr["AColumnName"].ToString());
}
string Manjson = Newtonsoft.Json.JsonConvert.SerializeObject(dictionary1);

DataTable 看起来像这样:

Sr.No TColumnName AColumnName
----- ----------- -----------
1     Apple       Lion
2     Orange      Tiger
3     Mango       Fox
4     Orange      Wolf

在上面的table中,前3行已成功添加到dictionary1中;然而,当我们尝试添加第四行时,它给出了错误。

我想要的 JSON 重复值结构如下所示:

{"Apple":"Lion", "Orange":["Tiger","Wolf"], "Mango":"Fox"}

是否可以从 table 创建此 JSON 结构?

当然可以。在你的循环中,你只需要检查键是否已经存在于字典中并采取适当的行动。一共有三种情况:

  • 密钥不存在,请按照您现在的操作进行添加。
  • 键存在,现存值为字符串,此时需要用包含旧字符串值和新字符串值的列表替换。
  • 键已经存在,并且现有的值是一个列表,在这种情况下,您只需将新字符串添加到列表中即可。

代码如下所示:

foreach (DataRow dr in dt_MappedColumns.Rows)
{
    string key = dr["TColumnName"].ToString();
    string value = dr["AColumnName"].ToString();

    if (!dictionary1.ContainsKey(key))
    {
        // key does not already exist, so add it
        dictionary1.Add(key, value);
    }
    else
    {
        // key exists, get the existing value
        object existingValue = dictionary1[key];

        if (existingValue is string)
        {
            // replace the existing string value with a list
            dictionary1[key] = new List<string> { (string)existingValue, value }; 
        }
        else
        {
            // the existing value is a list, so add the new value to it
            ((List<string>)existingValue).Add(value);
        }
    }
}

Fiddle: https://dotnetfiddle.net/PERc0D