2

假设您有一些 JSON:

{
    "status": "error",
    "data": {
        "errormessage": "Could not get user with ID: -1.",
        "errorcode": 14
    }
}

对于给定的错误结构:

struct APIError: Decodable {
    let code: Int?
    let message: String?

    enum CodingKeys: String, CodingKey {
        case code = "errorcode"
        case message = "errormessage"
    }
}

点击 Web 服务,获取 JSON,然后初始化结构:

let urlRequest = URLRequest(url: url)
let session = URLSession.shared
let task = session.dataTask(with: urlRequest)
{ (data, response, error) in
    // Doesn't work because the portion of the JSON we want is in the "data" key
    let e = try? JSONDecoder().decode(APIError.self, from: data)
}
task.resume()

有没有一些简单的方法可以做类似的事情data["data"]?要遵循的正确模型是什么?

解决方案 A - 将数据转换为 JSON 对象,获取我们想要的对象,然后将其转换为 Data 对象并进行解码。

let jsonFull = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String: Any]
let json = jsonFull["data"]
let data_error = try? JSONSerialization.data(withJSONObject: json, options: [])
let e = try? JSONDecoder().decode(APIError.self, from: data_error)

解决方案 B - 将目标项包装在另一个结构中

struct temp : Decodable {
    let status: String?
    let data: APIError?
}

let e = try? JSONDecoder().decode(temp.self, from: data).data

解决方案 C - 在 decode 中设置嵌套结构(如果它是几个对象深怎么办?)

let e = try? JSONDecoder().decode([Any, APIError.self], from: data)

我错过了什么模式?最优雅的方法是什么?

4

1 回答 1

0

您可以使用以下方法:

struct APIError: Decodable {
    let code: Int
    let message: String

    enum CodingKeys: String, CodingKey {
        case data
    }

    enum ErrorCodingKeys: String, CodingKey {
        case code = "errorcode"
        case message = "errormessage"
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        let nestedContainer = try container.nestedContainer(keyedBy: ErrorCodingKeys.self, forKey: .data)

        code = try nestedContainer.decode(Int.self, forKey: .code)
        message = try nestedContainer.decode(String.self, forKey: .message)
    }
}

let data = try! JSONSerialization.data(withJSONObject: ["status": "error", "data": ["errorcode": 14, "errormessage": "Could not get user with ID: -1."]], options: [])
let error = try! JSONDecoder().decode(APIError.self, from: data)
于 2018-01-24T17:16:24.867 回答