JSON解码问题?/我如何调试这个?



我正在进行API调用并管理接收到的数据,但我的调用正在捕获错误。下面是我的getData()代码:

func getData(from url: String) {
URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: { data, response, error in
guard let data = data, error == nil else {
print("something went wrong.")
return
}
do {
self.instructionsResults = try JSONDecoder().decode([Step].self, from: data)
print("getData() was successful!")
print(self.instructionsResults)
} catch {
print("Decoding error:")
print(String(describing: error)) // <-- this pings
}
}).resume()
}

下面是一个示例url json data: link

这是我为这个fetch定义的结构体:

struct Step: Codable {        
let number: Int
let step: String?
}

这可能是额外的,但我使用上面的调用来填充作为var steps: [String] = []实例化的数组,其中包含JSON step数组中每个步骤的字符串数据。

for n: Int in 0 ..< instructionsResults.count {
if instructionsResults[n].step != nil {
let step = instructionsResults[n].step ?? "n/a"
print("step: (instructionsResults[n].step)")
print("step: (step)")
steps.append(step)
}
}
print("Steps: (steps)")
}

有谁知道哪里出了问题吗?最后的print语句总是返回为空。我已经做了一个类似类型的调用格式化类似的方式在这个项目的早些时候,这工作得很好,所以我被难住了,我在哪里出错了。如有任何意见或反馈,我将不胜感激,谢谢。

编辑下面是错误代码:

Steps: []
Decoding error:
keyNotFound(CodingKeys(stringValue: "number", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: "number", intValue: nil) ("number").", underlyingError: nil))

顶级对象中没有number

请仔细阅读JSON。您忽略了根级别的对象,即键为steps的数组。

你需要这个

struct Root: Decodable { 
let steps: [Step]
}
struct Step: Decodable {        
let number: Int
let step : String
}

和解码

.decode([Root].self,

最新更新