kieron kieron - 3 months ago 12
ASP.NET (C#) Question

C# ASP.NET json objects to array

I am stuck on this error. This is my JSON data:

{
"date": "2016-08-26",
"time_of_day": "14:19",
"request_time": "2016-08-26T14:19:59+01:00",
"station_name": "Derby",
"station_code": "DBY",
"departures": {
"all": [
{
"mode": "train",
"service": "22152000",
"train_uid": "C65080"
},
{
"mode": "train",
"service": "22150000",
"train_uid": "C65145"
},
{
"mode": "train",
"service": "22180008",
"train_uid": "C70700"
}
]
}
}


What I am trying to do is add the service json object to an array, after this I want to increment through the service list and add each service to a separate API call. This is my code:

dynamic content = JsonConvert.DeserializeObject(json);
dynamic departures = content.departures;
dynamic DepartTimes = departures.all;
JArray items = ((JArray)DepartTimes["service"]);
int serviceLength = items.Count;


for (int i = 0; i < serviceLength; i++)
{
//next api call containing array increment
}


The error seems to be here :

JArray items = ((JArray)DepartTimes["service"]);


Any help is much appreciated, thank you!

Answer

One possible way is -

var json = "json";
dynamic d = JsonConvert.DeserializeObject(json);

JArray arr = new JArray();
foreach(JObject o in d.departures.all){
    arr.Add(o["service"]);
}

Console.Write(arr.Count); //output : 3