Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly deserialize and iterate over an array of JSON objects

Tags:

json

c#

In my app, I'm getting some data in a string format, which I'm converting to json:

string stringValue = System.Text.Encoding.Default.GetString(message.Value);

var jsonValue = JsonConvert.DeserializeObject(stringValue);

The resulting json string looks like this:

[
  {
    "LOCATION_ID": 2800,
    "CITY": "Sao Paulo"
  },
  {
    "LOCATION_ID": 1700,
    "CITY": "Seattle"
  },
  {
    "LOCATION_ID": 2300,
    "CITY": "Singapore"
  },
  {
    "LOCATION_ID": 1600,
    "CITY": "South Brunswick"
  },
  {
    "LOCATION_ID": 1500,
    "CITY": "South San Francisco"
  },
  {
    "LOCATION_ID": 1400,
    "CITY": "Southlake"
  },
  {
    "LOCATION_ID": 2600,
    "CITY": "Stretford"
  },
  {
    "LOCATION_ID": 2200,
    "CITY": "Sydney"
  }
]

What syntax can I use to iterate over this json array, and print out one json object at a time?

like image 228
Eugene Goldberg Avatar asked Sep 03 '25 02:09

Eugene Goldberg


1 Answers

What syntax can I use to iterate over this json array, and print out one json object at a time?

Define a model:

public class MyModel
{
    public int LOCATION_ID { get; set; }

    public string CITY { get; set; }
}

and then deserialize to this model:

var models = JsonConvert.DeserializeObject<IList<MyModel>>(stringValue);

and now you are free to iterate with standard C# iteration constructs like the foreach keyword:

foreach (MyModel model in models)
{
    Console.WriteLine(model.LOCATION_ID);
    Console.WriteLine(model.CITY);
}
like image 88
Darin Dimitrov Avatar answered Sep 05 '25 20:09

Darin Dimitrov