我正在使用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中使用以下格式访问文本和值
{
"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"
}
答案 0 :(得分:0)
试用此代码:
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"))
}
}