【发布时间】:2020-11-20 09:21:18
【问题描述】:
根据我的数据,我很确定我的模型是正确的,但我无法弄清楚为什么会出现格式错误?
JSON:
{
"1596193200":{
"clientref":1,
"type":"breakfast"
},
"1596200400":{
"clientref":0,
"type":"lunch"
},
"1596218400":{
"clientref":2,
"type":"dinner"
}
}
型号:
struct Call: Decodable {
let clientref: Int?
let type: String?
}
使用从 URL 解码 json 数据的代码编辑更新的问题:
class CallService {
static let shared = CallService()
let CALLS_URL = "url.com/Calls.json"
func fetchCalls(completion: @escaping ([Call]) -> ()) {
guard let url = URL(string: CALLS_URL) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
// handle error
if let error = error {
print("Failed to fetch data with error: ", error.localizedDescription)
return
}
guard let data = data else {return}
do {
let call = try JSONDecoder().decode([Call].self, from: data)
completion(call)
} catch let error {
print("Failed to create JSON with error: ", error.localizedDescription)
}
}.resume()
}
}
【问题讨论】:
-
试过
Codable而不是Decodable? -
显示您正在解码的代码。我希望你做到了
try decoder.decode([String: Call].self...但这是一个猜测。 -
错误仍然与
codable相同。我已将我的解码文件添加到问题中。 -
print("Failed to create JSON with error: ", error.localizedDescription)=> `print("Failed to create JSON with error: ", error),这样好多了,并给出错误。我们可以很容易地猜出哪里出了问题,但重要的是你要学会在哪里寻找错误,并把它做好。此外,如果它失败了,请不要犹豫:print("It failed with data stringified: \(String(data: data, encoding: .utf8)")),就在错误之后。 -
@Larme 谢谢!非常有帮助。我现在收到了错误
"Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))