如何访问JSON数组以显示Trip部分中的“ AdjustedScheduleTime”输出?
我使它可以用于StopLabel,如下所示,但是我正在努力访问AdjustedScheduleTime。
我尝试了以下操作:
[“ GetNextTripsForStopResponse”] [“ GetNextTripsForStopResult”] [“ Route”] [“ RouteDirection”] [“ Trips”] [“ Trip”] [“ AdjustedScheduleTime”]
但不起作用。
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let parameters = [
"appID": "5rt5rydg", //incorrect appID
"apiKey": "3b5fb15rdgy5454hdrfhr", //incorrect apiKey
"routeNo": "14",
"stopNo": "8600",
"format": "JSON"
]
AF.request("https://api.octranspo1.com/v1.2/GetNextTripsForStop?", method: .post, parameters: parameters,encoding:
URLEncoding.httpBody, headers: nil).responseJSON{ response in
let swiftyJsonVar = JSON(response.result.value!)
print(swiftyJsonVar)
if let busInfo = swiftyJsonVar["GetNextTripsForStopResult"]["StopLabel"].string {
print(": ",busInfo)
print("Label1: ", self.label1.text = busInfo)
}
}
}
这是结果:
{
"GetNextTripsForStopResult" : {
"Error" : "",
"Route" : {
"RouteDirection" : {
"RouteLabel" : "St-Laurent",
"Error" : "",
"RequestProcessingTime" : "20190112151425",
"Trips" : {
"Trip" : [
{
"AdjustmentAge" : "0.38",
"GPSSpeed" : "0.5",
"Latitude" : "45.429457",
"Longitude" : "-75.684117",
"TripDestination" : "St-Laurent",
"LastTripOfSchedule" : false,
"TripStartTime" : "14:31",
"BusType" : "4LB - IN",
"AdjustedScheduleTime" : "11"
},
{
"AdjustmentAge" : "4.32",
"GPSSpeed" : "0.5",
"Latitude" : "45.413749",
"Longitude" : "-75.689748",
"TripDestination" : "St-Laurent",
"LastTripOfSchedule" : false,
"TripStartTime" : "14:46",
"BusType" : "4LB - IN",
"AdjustedScheduleTime" : "22"
},
{
"AdjustmentAge" : "0.55",
"GPSSpeed" : "31.3",
"Latitude" : "45.399587",
"Longitude" : "-75.727631",
"TripDestination" : "St-Laurent",
"LastTripOfSchedule" : false,
"TripStartTime" : "15:01",
"BusType" : "4L - IN",
"AdjustedScheduleTime" : "37"
}
]
},
"RouteNo" : 14,
"Direction" : "Eastbound"
}
},
"StopLabel" : "MCARTHUR \/ IRWIN MILLER",
"StopNo" : "8600"
}
}
:MCARTHUR / IRWIN MILLER //这是StopLabel所需的输出
答案 0 :(得分:0)
好,那么您是否解释JSON。这是一个镜头。
{
表示字典时,您接下来必须选择一个键[
时,它表示数组。您必须选择一个索引"SomeString":
时,它是数组中的键。 {
开始。我们有字典!我们希望接下来会看到一些键。"GetNextTripsForStopResult"
。到目前为止,我们有:swiftyJsonVar["GetNextTripsForStopResult"]
Error
,Route
,StopLabel
等。让我们选择一个钥匙。由于我们尝试获取“ AdjustedScheduleTime”,因此选择Route
。到目前为止,我们有["GetNextTripsForStopResult"]["Route"]
Route
的内容。它再次是字典。 Trip
。您应该有["GetNextTripsForStopResult"]["Route"]["RouteDirection"]["Trips"]["Trip"]
Trip
中的内容是什么?它是一个数组!["GetNextTripsForStopResult"]["Route"]["RouteDirection"]["Trips"]["Trip"][2]
AdjustedScheduleTime
。因此,让我们选择它!
["GetNextTripsForStopResult"]["Route"]["RouteDirection"]["Trips"]["Trip"][2]["AdjustedScheduleTime"]
这些硬编码索引几乎从不是您想要的。也许您需要向用户显示所有AdjustedScheduleTime
或让用户选择其中一个,或将所有这些加起来。这实际上取决于您的应用程序和您要完成的工作。我在不了解您的应用程序,所调用的api以及您要实现的目标的情况下任意选择了最后一个索引(2)。您很可能不希望最后一个索引。