我有一个 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 )
}