使用ExpandoObject和IDictionary创建JSON时,允许同一键具有多个值 [英] Allow multiple values for the same key when creating JSON using ExpandoObject and IDictionary

查看:199
本文介绍了使用ExpandoObject和IDictionary创建JSON时,允许同一键具有多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to create dynamic JSON using ExpandoObject and IDictionary.

在动态创建JSON的过程中,可能会出现Name或Value重复的情况.但是,将重复的Name或Value添加到ExpandoObject时,会出现错误:

During the dynamic creation of JSON there could be instances when the Name or Value would repeat. However when adding the repeated Name or Value to the ExpandoObject, it gives an error:

已经添加了具有相同键的项目.

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

在上表中,前3行已成功添加到dictionary1中;但是,当我们尝试添加第四行时,会出现错误.

In the above table the first 3 Rows are added successfully into dictionary1; however, when we try to add the fourth Row, it gives the error.

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

My desired JSON structure for repeated values would look like this:

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

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

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

Is it possible to create this JSON structure from the table?

推荐答案

当然可以.在循环内部,您只需要检查字典中是否已存在键并采取适当的措施即可.共有三种情况:

Sure this is possible. Inside your loop you just need to check whether the key already exists in the dictionary and take the appropriate action. There are three cases:

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

代码如下:

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);
        }
    }
}

提琴: https://dotnetfiddle.net/PERc0D

这篇关于使用ExpandoObject和IDictionary创建JSON时,允许同一键具有多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆