gpt4 book ai didi

json - 快速解析JSON文件

转载 作者:行者123 更新时间:2023-11-28 15:01:33 38 4
gpt4 key购买 nike

我试图在 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/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com