json - 快速解析JSON文件

标签 json swift parsing

我试图在 tableView 中显示从 json 文件收集的数据,如下所示:https://api.tfl.gov.uk/journey/journeyresults/1000266/to/1000013

我只想显示每个旅程的摘要和描述。我试过类似的东西:

               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()
            }

 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")
            }

但我仍然无法正确解析。有人能帮我吗?

最佳答案

首先请在 JSON 查看器中检查您的响应 Here

然后检查您的字典,您直接使用数组“journeyArray”中的键“summary”,您可以在“legs”数组 -> “instruction”字典中找到“summary”键。

所以照此去做。

最好的方法是使用 https://github.com/tristanhimmelman/AlamofireObjectMapper它会自动将 JSON 转换为您的响应数据。

关于json - 快速解析JSON文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48865529/

相关文章:

javascript - 在 Javascript 中添加数组对象中对象的值

Swift:有最大计时器速度吗?

parsing - 是否可以使用递归下降解析器来验证语法并同时构建解析树?

java - Jackson 忽略@Ignore 注释

c# - 如何解析在 MVC Controller 中收到的 JSON

ios - 在 ios 的 mapbox gl 中创建一个圆圈

用于对象初始化的 Java CLI 参数语法

java - 如何解析 JSON 文件并使用它来创建类对象?

python 解析带双引号的json数据

swift - 为什么在泛型类型已知时传入它