Parse a JSON array using json.NET and C #

I have some data in the following JSON format that I need to parse:

{ "status":0, "timestamp":"8:20pm", "routes":[ { "directions":[ "E Towne", "ETP" ], "routeID":"30" }, { "directions":[ "Johnson", "Observatory" ], "routeID":"81" } ] } 

Using json.net, I need to get the following output:

30 E Towne - ETP

81 Johnson - Observatory

Using the following code, I get the following incorrect output:

30 E Towne - ETP

81 E Towne - ETP

How to write elements of a direction array to the corresponding routeID element? My code is:

 public class Route { public string routeID { get; set; } public string directions { get; set; } } private void routeClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { string jsonResults_routes = e.Result; JObject routeData = JObject.Parse(jsonResults_routes); JArray routeIdArray = (JArray)routeData["routes"]; JArray routeDirections = (JArray)routeData["routes"][0]["directions"]; List<Route> l = new List<Route>(); for (int i = 0; i < routeIdArray.Count; i++) { Route BusRoutes = new Route(); JObject routeIDarrayObject = (JObject)routeIdArray[i]; BusRoutes.routeID = (string)routeIDarrayObject["routeID"]; string sep = " - "; string bothDirections = String.Join(sep, routeDirections); List<string> sc = new List<string>(); string[] direction = new string[]{bothDirections}; sc.AddRange(direction); foreach (string direx in sc) { BusRoutes.directions = direx; } l.Add(BusRoutes); } var newList = l.OrderBy(x => x.routeID).ToList(); lbRoutesData.ItemsSource = newList; } 
+4
source share
2 answers

@competent_tech is correct in the analysis. If I can offer, I think it will be more natural if you work with real objects. For instance:

 public class RouteInfo { public List<string> Directions { get; set; } public string RouteID { get; set; } } public class RouteData { public int Status { get; set; } public string Timestamp { get; set; } public List<RouteInfo> Routes { get; set; } } 

And in your method:

 var routeData = JsonConvert.DeserializeObject<RouteData>(e.Result); return routeData.Routes .Select(r => new Route { routeId = r.RouteID, directions = String.Join(" - ", r.Directions) }) .OrderBy(r => r.routeId) .ToList(); 

Or, in a more natural way, manipulate an object of a type in other ways.

Edit:. For an easy way to create classes based on a JSON string, go to json2csharp .

+5
source

This is because your routeDirections specifically requests the first element in the array:

 JArray routeDirections = (JArray)routeData["routes"][0]["directions"]; 

You need to move this logic inside the loop and use the current loop pointer:

 for (int i = 0; i < routeIdArray.Count; i++) { Route BusRoutes = new Route(); JObject routeIDarrayObject = (JObject)routeIdArray[i]; BusRoutes.routeID = (string)routeIDarrayObject["routeID"]; JArray routeDirections = routeIDarrayObject["directions"]; 
+2
source

Source: https://habr.com/ru/post/1489945/