我正在尝试使用 ExpandoObject 和 IDictionary 创建动态 JSON。
在动态创建 JSON 的过程中,可能会出现名称或值重复的情况。但是,当将重复的名称或值添加到 ExpandoObject 时,会出现错误:
已添加具有相同密钥的项目。
下面是我的代码片段:
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);
The DataTable
看起来像这样:
Sr.No TColumnName AColumnName
----- ----------- -----------
1 Apple Lion
2 Orange Tiger
3 Mango Fox
4 Orange Wolf
在上表中,前 3 行已成功添加到dictionary1
;但是,当我们尝试添加第四行时,会出现错误。
我想要的重复值的 JSON 结构如下所示:
{"苹果":"狮子", "橙子":["老虎","狼"], "芒果":"狐狸"}
是否可以从表创建此 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 https://dotnetfiddle.net/PERc0D
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)