1

im using the next code:

dynamic jsonObj = JsonConvert.DeserializeObject(reader.ReadToEnd());

foreach (var item in jsonObj)

{

 Console.WriteLine("");

}

Where reader.ReadToEnd() has a json string.

But i have an error on foreach,

Error 13 foreach statement cannot operate on variables of type 'System.Collections.IEnumerable' because 'System.Collections.IEnumerable' does not contain a public definition for 'GetEnumerator' C:\Users\myUser\Desktop\app\appRecept\Paises.cs 47 29 appPreregistro

2
  • 1
    How does your json structure look like? Does it look like an array or a list in watch window? Commented Jan 26, 2016 at 19:57
  • my json looks like this: { "success" : "true", "states" : [ { "id" : "1000", "name" : "AGUASCALIENTES", }, { "id" : "1001", "name" : "BAJA CALIFORNIA", }, { "id" : "1002", "name" : "BAJA CALIFORNIA SUR", }, { "id" : "1004", "name" : "ZACATECAS", } ] } Commented Jan 26, 2016 at 22:20

1 Answer 1

1

If you're deserializing an array of objects from JSON, something that looks like this:

[
  {blah},
  {blah},
  {blah}
]

then deserialize to a List type:

var jsonObj = JsonConvert.DeserializeObject<List<dynamic>>(reader.ReadToEnd());
Sign up to request clarification or add additional context in comments.

2 Comments

my json looks like this: { "success" : "true", "states" : [ { "id" : "1000", "name" : "AGUASCALIENTES", }, { "id" : "1001", "name" : "BAJA CALIFORNIA", }, { "id" : "1002", "name" : "BAJA CALIFORNIA SUR", }, { "id" : "1004", "name" : "ZACATECAS", } ] } The way you deserialize the string object throug an exception : Cannot deserialize the current JSON object into type list, because the type requires a JSON array
If you want to loop through the states, then change your loop to: foreach (var item in jsonObj.states)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.