2016-11-06 17 views
0

從以下JSON數據中,我想將station_code變量放入列表中。在此之後,我想將每個station_code變量用於API URL調用。C#如何遍歷各個API調用的列表

{ 
    "request_time": "2015-02-19T08:33:39+00:00", 
    "stations": [ 
    { 
     "station_code": "HWV", 
     "atcocode": null 
    }, 
    { 
     "station_code": "HXX", 
     "atcocode": null 
    }, 
    { 
     "station_code": "HAF", 
     "atcocode": null 
    } 
] 
} 

這是我一直在嘗試此

dynamic array = JsonConvert.DeserializeObject(json); 
     dynamic stations = array.stations; 

     var test = JObject.Parse(json); 
     var services = test.SelectTokens("stations[*].station_code").Select(t => (string)t).ToList(); 

     JArray items = new JArray(); 
     foreach (JObject station in stations) 
     { 
      items.Add(station["station_code"]); 



     } 

     int stationLength = 3; 

     for (int i = 0; i < stationLength; i++) 
     { 
      string localJson = get_local_departs("http://transportapi.com/v3/uk/train/station/"+ items[i] + "/live.json?app_id=03bf8009&app_key=d9307fd91b0247c607e098d5effedc97&train_status=passenger"); 

      dynamic localStationArray = JsonConvert.DeserializeObject(localJson); 
      dynamic departures = localStationArray.departures; 
      dynamic localStationDeparts = departures.all; 

      foreach (var depart in localStationDeparts) 
      { 
       //info put into data tables 

      } 
     } 
    } 

回答

0

那麼C#代碼爲什麼不能將其轉換成一個強類型並使用它像

public class stations 
{ 
    public string station_code { get; set; } 
    public string atcocode {get; set; } 
} 

public class Data 
{ 
public DateTime request_time {get; set; } 
public IEnumerable<stations> Stations {get; set; } 
} 

var result = JsonConvert.DeserializeObject<Data>(json); 

foreach(stations s in result.Stations) 
{ 
    Console.WriteLine(s.station_code); 
} 
+0

因爲我需要把station_code變量放到一個列表中,這樣我就可以針對每個API調用分別迭代它們。 – kieron