JSON的值可以是Array和Object

JSON的值可以是Array和Object

我向服务器发出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)
                }
            }

最佳答案

一种可能的解决方案是使用单个结构,例如:

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为零。

可能不是最漂亮的解决方案,但至少您没有在重复结构。

关于json - JSON的值可以是Array和Object,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51723591/

10-13 00:47