1

我有一个 API 的 json 响应。这也返回一个值,它是一个字典。如何实现仅存储/映射此字典的值。这是一个可以简单地放入操场的示例:

id = ["$oid": "591ae6cb9d1fa2b6e47edc33"]

应该只是

id = "591ae6cb9d1fa2b6e47edc33"

这是一个可以简单地放入操场的示例:

import Foundation

struct Location : Decodable {
    enum CodingKeys : String, CodingKey {
        case id = "_id"
    }
    var id : [String:String]? // this should be only a string with the value of "$oid"
}

extension Location {
    public init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        id = try values.decode([String:String]?.self, forKey: .id)
    }
}


var json = """
[
    {
        "_id": {
            "$oid": "591ae6cb9d1fa2b6e47edc33"
        }
    },
    {
        "_id": {
            "$oid": "591ae6cd9d1fa2b6e47edc34"
        }
    }
]

""".replacingOccurrences(of: "}\n{", with: "}\\n{").data(using: .utf8)!

let decoder = JSONDecoder()

do {
    let locations = try decoder.decode([Location].self, from: json)
    locations.forEach { print($0) }
} catch {
    print(error.localizedDescription )
}
4

1 回答 1

1

你几乎在那里:

struct Location {
    var id: String
}

extension Location: Decodable {
    private enum CodingKeys: String, CodingKey {
        case id = "_id"
    }

    public init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        let _id = try values.decode([String: String].self, forKey: .id)
        id = _id["$oid"]!
    }
}

如果您_id在 JSON 数据中有 mote 键,我强烈建议您创建一个私有结构来表示该结构,以确保类型安全。

于 2017-07-15T08:46:51.893 回答