代码之家  ›  专栏  ›  技术社区  ›  TommyBs

JSONDecoder-解码字符串值以更正类型

  •  0
  • TommyBs  · 技术社区  · 7 年前

    如果我将这些值指定为 Date 和 Double 它分别抛出一个错误 Expected to decode Double but found a string

    Struct Place {
        var created_at: Date?
        var longitude: Double?
        var latitude: Double?
    
    }
    

    我在网上看到过一些处理日期格式的例子,但我不确定如何处理双值?

    init(from decoder:Decoder)

    例如

    init(from decoder:Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        longitude = try values.decode(Double.self, forKey: .longitude) //returns nil but using String works fine
    }
    

      longitude = Double(try values.decode(String.self, forKey: .longitude))
    

    但还有别的办法吗?

    此外,我实际上有许多其他属性可以很好地转换,但是通过对这3个属性进行这项工作,我现在必须在其中添加所有其他属性,这似乎有点多余。有没有更好的办法?

    1 回复  |  直到 7 年前
        1
  •  1
  •   vadian    7 年前

    如果JSON值为 String 你必须解码 字符串 . 隐式类型转换 Double 这是不可能的。

    可以通过添加计算变量来避免自定义初始值设定项 coordinate ,在本例中 CodingKeys

    import CoreLocation
    
    struct Place : Decodable {
    
        private enum CodingKeys: String, CodingKey { case createdAt = "created_at", longitude, latitude}
    
        let createdAt: Date
        let longitude: String
        let latitude: String
    
        var coordinate : CLLocationCoordinate2D {
            return CLLocationCoordinate2D(latitude: Double(latitude) ?? 0.0, longitude: Double(longitude) ?? 0.0)
        }
    }