我正在解码JSON结构,如果它无法解码,此时我的错误检查意味着服务器响应中缺少其中一个字段,我想向用户显示。
解码此结构时:
struct UserResponseObject: Decodable {
let message: String
let data: User
}
这里
do {
let responseObject = try createDecoder().decode(UserResponseObject.self, from: jsonData)
//print("RESPONSE MESSAGE: ", responseObject.message)
//print("GET USER DATA: ",responseObject.data)
completion!(.success(responseObject.data))
} catch let error as NSError {
print("failure to decode user from JSON")
completion!(.failure(error))
}
如果没有字段.data,我想在catch块中的responseObject.message中返回消息。但我不允许将响应重新编码到此结构中。
struct ErrorObject: Decodable {
let message: String
}
第一次解码失败时,我应该如何尝试获取消息。感谢
答案 0 :(得分:0)
如果你的struct实现可编码,那么你最好使用JSONEncoder& JSONDecoder
struct Language: Codable {
var name: String
var version: Int
}
let swift = Language(name: "Swift", version: 4)
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(swift) {
// save `encoded` somewhere
}
if let encoded = try? encoder.encode(swift) {
if let json = String(data: encoded, encoding: .utf8) {
print(json)
}
let decoder = JSONDecoder()
if let decoded = try? decoder.decode(Language.self, from: encoded) {
print(decoded.name)
}
答案 1 :(得分:0)
如果json中缺少任何字段,则应首先使其成为可选字段。在你的情况下应该是,
struct UserResponseObject: Decodable {
let message: String? // You should decide, should it be optional or not
let data: User? // You should decide, should it be optional or not
}
另外你应该在do块中处理无数据的情况......
因此,在try-catch块中尝试创建UserResponseObject
object;
do {
let responseObject = try createDecoder().decode(UserResponseObject.self, from: jsonData)
//print("RESPONSE MESSAGE: ", responseObject.message)
//print("GET USER DATA: ",responseObject.data)
if(responseObject.data) {
completion!(.success(responseObject.data))
}
else {
completion!(.failure(//no data error handler))
}
} catch let error as NSError {
let responseObject = UserResponseObject(message: error.localizedDescription, data: nil)
print("failure to decode user from JSON")
completion!(.failure(error))
}
答案 2 :(得分:0)
您可以通过添加更多catch块来了解错误的确切性质:
do {
let messages = try JSONDecoder().decode(Results.self, from: data)
} catch DecodingError.dataCorrupted(let context) {
print(context)
} catch DecodingError.keyNotFound(let key, let context) {
print("Key '\(key)' not found:", context.debugDescription)
print("codingPath:", context.codingPath)
} catch DecodingError.valueNotFound(let value, let context) {
print("Value '\(value)' not found:", context.debugDescription)
print("codingPath:", context.codingPath)
} catch DecodingError.typeMismatch(let type, let context) {
print("Type '\(type)' mismatch:", context.debugDescription)
print("codingPath:", context.codingPath)
} catch {
print("error: ", error)
}