【发布时间】:2019-12-17 17:13:13
【问题描述】:
我正在尝试将返回的 JSON 转换为字典以供使用,但由于某种原因,它无法正常工作。我也没有收到任何错误,这就是为什么我真的很难过。
此块将显示我的序列化和转换。我的第一个打印语句被命中,但第二个打印语句从未到达。
do {
let jsonAny = try JSONSerialization.jsonObject(with: data, options: [])
print("made it through serialization")
guard let json = jsonAny as? [String: String] else { return } //also tried [String: Any]
print("passed the guard let")
let fish = self.parseFishManual(json: json)
//print(fish.name)
//print(fish.scientific)
} catch {
debugPrint(error.localizedDescription)
return
}
对此的任何帮助表示赞赏!
编辑: json可以通过以下链接查看(添加一个从1到24的数字以查看单个数据) https://thefishapi.herokuapp.com/api/fish/
这是整个 URL 会话函数:
func getFishSpeciesUrlSession() {
guard let url = URL(string: URL_SPECIES) else { return }
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard error == nil else {
debugPrint(error.debugDescription)
return
}
guard let data = data else { return }
do {
let jsonAny = try JSONSerialization.jsonObject(with: data, options: [])
print("made it through serialization")
guard let json = jsonAny as? [String: Any] else { return }
print("passed the guard let")
let fish = self.parseFishManual(json: json)
print(fish.name)
print(fish.scientific)
} catch {
debugPrint(error.localizedDescription)
return
}
//print("Data = \(data)")
//print("Response = \(response)")
}
这是我的 parseFishManual 方法:
private func parseFishManual(json: [String: Any]) -> Fish {
let name = json["name"] as? String ?? ""
let scientific = json["scientific"] as? String ?? ""
let environment = json["environment"] as? String ?? ""
let biology = json["biology"] as? String ?? ""
let description = json["description"] as? String ?? ""
let fish = Fish(name: name, scientific: scientific, environment: environment, biology: biology, description: description)
return fish
}
【问题讨论】:
-
jsonAny 不是 [String:String]。显示您的实际 JSON。
-
你应该转换成
[String: Any],如果你的JSON的根是一个数组,甚至是[Any]。 -
所以我也使用了
String: Any,但我最终得到了相同的结果。没有错误信息,也没有打印数据。有什么其他错误的想法吗?当我回到电脑前时,我会用更多代码更新我的问题。