我向服务器发出HTTP请求,并收到JSON文档。 我具有以下结构来解码JSON:
struct DocumenJSON: Codable {
let code: Int?
let description: String?
let value: Value?
}
问题在于,使请求“ A”得到一个对象值,使请求“ B”成为一个值数组,因此该结构应为:
struct DocumenJSONArray: Codable {
let code: Int?
let description: String?
let value: [Value]?
}
在没有重复代码的情况下,如何在Swift 4中实现呢?
} catch let jsonErr {
print("Error serializing json:", jsonErr)
do {
document = try JSONDecoder().decode(DocumenJSON.self, from: data)
user = User.init(password: "", email: document?.value?.email ?? "Empty", givenNames: document?.value?.nickname ?? "Empty", familyName: document?.value?.lastname ?? "Empty", phone: document?.value?.nickname ?? "Empty")
} catch let jsonErr2 {
print("Error serializing json2:", jsonErr2)
}
}
答案 0 :(得分:0)
可能的解决方案是使用单个结构,例如:
extension DocumenJSON: Decodable {
enum CodingKeys: String, CodingKey {
case code
case description
case valueAsObject
case valueAsArray
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
code = try values.decodeIfPresent(Int.self, forKey: .code)
description = try values.decodeIfPresent(String.self, forKey: .description)
valueAsObject = try values.decodeIfPresent(Value.self, forKey: .valueAsObject)
valueAsArray = try values.decodeIfPresent(Array.self, forKey: .valueAsArray)
}
}
现在,每当调用DocumenJSON
时,只需检查每个属性valueAsObject或valueAsArray为nil。
可能不是最漂亮的解决方案,但至少您没有在重复结构。