I am new to C# .net . I am trying to add my Jarray
to a dictionary Dictionary<string, dynamic>
and then to a list 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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.