2017-07-26 62 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(...)'这是一个稍微好一点的方便方法,更多的调试信息。 –