1
我有一個API的json響應。這將返回一個也是一個Dictionary的值。如何才能實現僅存儲/映射此字典的值。這裏是一個可以簡單地放入一個遊樂場的例子:Codable,只能從字典中解碼值
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)
}