2017-07-26 67 views
0

解碼JSONArray到特定字段我有此(IMHO低劣)JSON可編碼:通過指數

"geometry": { 
     "type": "Point", 
     "coordinates": [ 
      6.08235, 
      44.62117 
     ] 
} 

我想映射到此struct,滴陣列2個字段。

struct MMGeometry:Codable { 
    let type:String 
    let latitude: Double 
    let longitude: Double 
} 

JSONDecoder能夠做到這一點嗎?也許使用CodingKey

+0

你將不得不要麼提供的JSON,然後可以計算從這些屬性的佈局相匹配的嵌套類型,或者只是覆蓋'init(from:Decoder)'手動解碼。 –

回答

1

我去了手動解決方案:

struct Geometry:Codable { 
    let type:String 
    let latitude: Double 
    let longitude: Double 

    enum CodingKeys: String, CodingKey { 
     case type, coordinates 
    } 

    enum CoordinatesKeys: String, CodingKey { 
     case latitude, longitude 
    } 

    init (from decoder :Decoder) throws { 
     let container = try decoder.container(keyedBy: CodingKeys.self) 
     type = try container.decode(String.self, forKey: .type) 
     let coords:[Double] = try container.decode([Double].self, forKey: .coordinates) 
     if coords.count != 2 { throw DecodingError.dataCorruptedError(forKey: CodingKeys.coordinates, in: container, debugDescription:"Invalid Coordinates") } 

     latitude = coords[1] 
     longitude = coords[0] 
    } 

    func encode(to encoder: Encoder) throws { 

    } 
} 
+1

順便說一句,你可以拋出'DecodingError.dataCorruptedError(...)'這是一個稍微好一點的方便方法,更多的調試信息。 –