I have a dictionary of strings and object that i obtained deserializing this json answer:
{"labels":[{"id":"1","descrizione":"Etichetta interna","tipo":"0","template_file":"et_int.txt"},{"id":"2","descrizione":"Etichetta esterna","tipo":"1","template_file":"et_ext.txt"}],"0":200,"error":false,"status":200}
using the code:
var labels = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(json);
Now i want to loop only trought the objects inside the "labels" key. I tried
foreach (var outer in labels["labels"]){/* code */}
but i got error:
CS1579: foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'.
Solved replacing the dictionary with a class, thank you
A possible solution:
Otherwise, you can create a class with deserialization information and instruct the deserializer to deserialize your json string to that type:
Your problem is that you've defined the
Type
ofValue
for each dictionary entry asobject
. C# can't know how to loop over on object. So you need to work out what type is actually inside the object once theJavaScriptSerializer
have parsed the JSON. One way isOnce you know what type the serializer is creating, all you need to do is cast the object back to that type. For example, assuming it's a list of objects
Alternatively, if each object in the JSON is the same, you could try create the dictionary as the type you need. So you serializing becomes
You need to loop through your dictionary.
Once you start looping through it you will get access to key and value. Since you are interested to look at entry.value you can do operation on that easily. Currently your dictionary value is type of object which does not have an enumerator
Create a class to deserialize your json:
To create classes, you can copy the json in clipboard and use the
Edit / Paste special / Paste JSON as class
in visual studio (I use vs2013).
Could you please try below snippet? It might be help you.