【问题标题】:How to access nested key from dictionary using ObjectMapper?如何使用 ObjectMapper 从字典中访问嵌套键?
【发布时间】:2018-03-29 12:34:46
【问题描述】:

需要访问latlng。我该怎么做?

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

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

【问题讨论】:

  • 为什么不使用新的 Codable 协议?

标签: ios swift objectmapper


【解决方案1】:

你只需要:

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

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

【讨论】:

    【解决方案2】:

    您需要为包含latlng 属性的位置声明一个单独的类:

    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

    【讨论】:

    • 您确定your answer 有效吗? :D
    • 关于元素数组中第一个元素的相同问题。你知道怎么做吗?
    • @BartłomiejSemańczyk 你能详细说明一下吗?
    • 我找到了答案:‘.0’
    【解决方案3】:

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

    【讨论】:

    • 是的,你是对的,但我经常需要更改它们的命名;)但你的回答很有帮助......
    【解决方案4】:

    希望对你有帮助

     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)
                                }
                          }
                     }
    

    【讨论】:

    • 该问题与使用JSONSerialization无关。即便如此,您的回答也没有提供正确的结果。
    • 但我在我的项目中使用了这个概念
    • 无论如何它对你没有帮助!但绝对是对一些开发者有帮助
    猜你喜欢
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-29
    • 2021-03-04
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多