2017-07-14 77 views
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) 
} 

回答

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"]! 
    } 
} 

如果您在JSON數據中有_id下的mote鍵,我強烈建議您創建一個私有結構體來代表類型安全性的結構。