[英]C# How to add Jarray to List<Dictionary<string, dynamic>>
I am new to C# .net .我是 C# .net 的新手。 I am trying to add my Jarray
to a dictionary Dictionary<string, dynamic>
and then to a list List<Dictionary<string, dynamic>>
.我正在尝试将我的Jarray
添加到字典Dictionary<string, dynamic>
然后添加到列表List<Dictionary<string, dynamic>>
。
My string is something like :我的字符串是这样的:
Response = "[{\"name\":\"ABCD\",\"caption\":\"ABCDCaption\",\"description\":\"ABCDDesc\"},{\"name\":\"ABCD\",\"caption\":\"ABCDCaption\",\"description\":\"ABCDCaption\"},{\"name\":\"XYZ.exe\",\"caption\":\"XYZCaption\","description":\"XYZdesc\"}]"
The code is :代码是:
JArray a = JArray.Parse(Response);
foreach (JObject o in bb.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
string name = p.Name;
var value = p.Value;
DicSQLData.Add(key: name, value: value);
}
ListSQLData.Add(DicSQLData);
}
It works fine for first set of data它适用于第一组数据
{\"name\":\"ABCD\",\"caption\":\"ABCDCaption\",\"description\":\"ABCDDesc\"}
For second set it gives error as dictionary does not add duplicate key.对于第二组,它会给出错误,因为字典没有添加重复键。 How to fix this?如何解决这个问题? Any help is really appreciated.任何帮助都非常感谢。
I think we're missing some of the code, but you're seeing that error because you're not initializing a new dictionary on each loop iteration, you're inserting into the same dictionary causing the key errors.我认为我们遗漏了一些代码,但是您看到该错误是因为您没有在每次循环迭代中初始化一个新字典,而是插入到导致关键错误的同一个字典中。
Try doing this instead.尝试这样做。 Notice each iteration makes a new dictionary and then inserts it into the list请注意,每次迭代都会创建一个新字典,然后将其插入到列表中
JArray a = JArray.Parse(Response);
foreach (JObject o in bb.Children<JObject>())
{
//make new dictionary
var DicSQLData = new Dictionary<string, dynamic>();
foreach (JProperty p in o.Properties())
{
string name = p.Name;
var value = p.Value;
DicSQLData.Add(key: name, value: value);
}
//add dictionary to list
ListSQLData.Add(DicSQLData);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.