【问题标题】:How can I access the value from the below format(NDictionary)?如何从以下格式(字典)访问值?
【发布时间】:2017-04-17 13:22:31
【问题描述】:

我正在使用 googlematrix api 调用,在下面我提到了响应。

这是我的代码

   let jsonObjects=responseObject as! NSDictionary
    var data = jsonObjects.data(using: .utf8)!
    if let parsedData = try? JSONSerialization.jsonObject(with: data) as! [String:Any] {
     let language = parsedData["rows"] as! [String:Any]
     print(language)
    let field = language["elements"] as! [[String:Any]]
    let name = field["distance"]!
    let text = field["text"]!
     print(text) // ==> Test1
}

我需要在swift3.0中访问以下格式的textvalue

{
       "destination_addresses" : [ "Chennai, Tamil Nadu, India" ],
       "origin_addresses" : [ "Madurai, Tamil Nadu, India" ],
       "rows" : [
          {
             "elements" : [
                {
                   "distance" : {
                      "text" : "488 km",
                      "value" : 487721
                   },
                   "duration" : {
                      "text" : "8 hours 32 mins",
                      "value" : 30690
                   },
                   "status" : "OK"
                }
             ]
          }
       ],
       "status" : "OK"
    }

【问题讨论】:

标签: json xcode swift3 nsdictionary


【解决方案1】:

试试这个代码:

let responseObject : NSDictionary! = YOUR RESPONSE

        let jsonObjects = responseObject as NSDictionary
        let array : NSArray! = jsonObjects.object(forKey: "rows") as! NSArray!

        for elmnt in array
        {
            let element = elmnt as! NSDictionary
            let ary_Element : NSArray! = element.object(forKey: "elements") as! NSArray!

            for data in ary_Element
            {
                let mDict = data as! NSDictionary

                let dict_Distance = mDict.value(forKey: "distance") as! NSDictionary
                let dict_Duration = mDict.value(forKey: "duration") as! NSDictionary

                print(dict_Distance.value(forKey: "text"))
                print(dict_Distance.value(forKey: "value"))
                print(dict_Duration.value(forKey: "text"))
                print(dict_Duration.value(forKey: "value"))
            }
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多