Reputation: 43
I am trying to display in a tableView the data gathered from a json file that looks like: https://api.tfl.gov.uk/journey/journeyresults/1000266/to/1000013
I want to display just the summary and description of each journey. I tried something like:
do{
let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSDictionary
print(fetchedData.value(forKey: "journey"))
if let journeyArray = fetchedData.value(forKey: "journey") as? NSArray{
for journey in journeyArray{
if let journeyDict = journey as? NSDictionary {
if let summary = journeyDict.value(forKey: "summary"){
self.summaryArray.append(summary as! String)
}
if let desc = journeyDict.value(forKey: "description"){
self.descArray.append(desc as! String)
}
OperationQueue.main.addOperation {
self.journeysTableView.reloadData()
}
}
}
}
self.journeysTableView.reloadData()
}
and
do{
let fetchedData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! Dictionary<String,AnyObject>
print(fetchedData)
for eachFetchedJourney in fetchedData{
let eachJourney = eachFetchedJourney as! [String: Any]
let summary = eachJourney["summary"] as! String
let description = eachJourney["description"] as! String
self.fetchedJourneys.append(Journey(summary: summary, description: description))
print(fetchedData)
}
self.journeysTableView.reloadData()
}
catch{
print("Error")
}
but I still can't get the parsing right. Would be anyone able to help me?
Upvotes: 0
Views: 46
Reputation: 27
First please check your response in JSON viewer Here
Then check your dictionary you are directly using Key 'summary' from your Array 'journeyArray', Where you can find your 'summary' key is in your 'legs' Array -> 'instruction' dictionary.
So Do It Accordingly.
The best way is Use https://github.com/tristanhimmelman/AlamofireObjectMapper which automatically converts JSON your response data.
Upvotes: 1