代码之家  ›  专栏  ›  技术社区  ›  Bartłomiej Semańczyk

如何使用ObjectMapper从字典中访问嵌套键?

  •  0
  • Bartłomiej Semańczyk  · 技术社区  · 8 年前

    enter image description here

    需要访问 lat lng 。我该怎么做?

    这就是我现在所做的,但它不起作用:

    latitude <- map["location"]["lat"]
    longitude <- map["location"]["lng"]
    
    4 回复  |  直到 8 年前
        1
  •  2
  •   Ahmad F    8 年前

    您只需要:

    latitude <- map["location.lat"]
    longitude <- map["location.lng"]
    

    目前为止 ObjectMapper 支持键内的点表示法,以便轻松映射嵌套对象(您可以在库文档的“轻松映射嵌套对象”下找到)。

        2
  •  2
  •   Ahmad F    8 年前

    您需要声明一个单独的类,以便该位置包含 lat 以及 lng 属性:

    class Location: Mappable {
        var lat: Double?
        var lng: Double?
    
        required init?(map: Map){ }
    
        func mapping(map: Map) {
            lat <- map["lat"]
            lng <- map["lng"]
        }
    }
    

    因此,您可以将其用作:

    class Base: Mappable {
        var location: Location?
        // ...
    
        required init?(map: Map){ }
    
        func mapping(map: Map) {
            location <- map["location"]
            //...
        }
    }
    

    它将表示用于映射基础对象的嵌套类型。


    旁白栏注: 您可能还需要检查 Codable - Encoding and Decoding Custom Types

        3
  •  1
  •   Shehata Gamal    8 年前

    您可以使用 JSONDecoder ,这将使您能够只在json中写入对象的键,而不是使用ObjectMapper写入两次。(作为属性和内部映射函数),尤其是如果服务器密钥命名适合您

        4
  •  -3
  •   Gowtham Sooryaraj    8 年前

    希望这对你有帮助

     let data = NSData(contentsOf: searchUrl as URL)
                    let json = try! JSONSerialization.jsonObject(with: data! as Data, options: JSONSerialization.ReadingOptions.allowFragments) as! [String:AnyObject]
                    let status = json["status"] as! String
                    print(status)
                    if status == "OK" {
                        if let result = json["results"] as? [[String:AnyObject]] {
                            if let geometry = result[0]["geometry"] as? [String:AnyObject] {
                                if let location = geometry["location"] as? [String:AnyObject] {
                                    lat = location["lat"] as! Double
                                    lng = location["lng"] as! Double
                                    print(lat)
                                    print(lng)
                                }
                          }
                     }