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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With