使用 JSON 数据检索到 Swift 数据类型



我正在尝试从URL获取数据。它很成功。我可以下载并转换为dictionary[String : Any],但响应在嵌套循环中。我不知道如何检索。有人可以建议如何在响应中获取文本和值吗?

func getDataFromUrl() {
  let url = URL(string: "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&departure_time=1408046331&origins=37.407585,-122.145287&destinations=37.482890,-122.150235")
  let request = NSMutableURLRequest(url: url!)
  let session = URLSession.shared
  request.httpMethod = "GET"
  let dataTask = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in
    do {
      let jsonData = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String: Any]
      let destinationAddress  = jsonData!["destination_addresses"]
      print("Destination address (String(describing: destinationAddress!))")
      let origin_addresses  = jsonData!["origin_addresses"]
      print("Origin_addresses (String(describing: origin_addresses!))")
      let rows  = jsonData!["rows"]
      print("Rows  (String(describing: rows!))")
      // Here I want to print text and value.
    } catch {
      // handle error
    }
  })
  dataTask.resume()
}

上面的答案有效,但在我看来,更快捷的方法是使用 Codable .

class MyResponseType:Codable {
    let destination_addresses:String
    let rows:[MyCustomRowData]
}
class MyCustomRowData:Codable {
    let elements:[MyCustomElementsData]
}
class MyCustomElementsData:Codable {
    // properties here
}

这样做,解析 json 是这样完成的:

let response = try? JSONDecoder().decode(MyResponseType.self, from: data)

其中data变量只是从请求中检索到的Data对象。

最初,您必须设置一些样板代码来复制预期的数据格式,但使用它确实是值得的(并且它使其高度可测试(。

当解码成功时,你有一个完美类型的对象,它也可以有可选。如果字段丢失或类型错误,它不会解码(这是一件好事(。

以下是解析text并从响应中Value的方法:

do{
            if let jsonData = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String: Any] {
                if let destinationAddress = jsonData["destination_addresses"] as? [String] {
                    print(destinationAddress) //["1 Hacker Way, Menlo Park, CA 94025, USA"]
                }
                if let origin_addresses = jsonData["origin_addresses"] as? [String] {
                    print(origin_addresses) //["3251 Hillview Ave, Palo Alto, CA 94304, USA"]
                }
                if let rows = jsonData["rows"] as? [[String: AnyObject]] {
                    if rows.indices.contains(0) {
                        if let elements = rows[0]["elements"] as? [[String: AnyObject]] {
                            for element in elements {
                                if let duration = element["duration"] as? [String: AnyObject] {
                                    let text = duration["text"] as? String ?? ""
                                    print(text) //17 mins
                                    let value = duration["value"] as? Int ?? 0
                                    print(value) //1010
                                }
                                if let distance = element["distance"] as? [String: AnyObject] {
                                    let text = distance["text"] as? String ?? ""
                                    print(text) //7.2 mi
                                    let value = distance["value"] as? Int ?? 0
                                    print(value) //11555
                                }
                            }
                        }
                    }
                }
            }
        }catch{ //error handle
        }

使用以下代码:

  let rows = jsonData["rows"] as! Array
  let element = rows[0] as! Dictionary
  let elementArray = element.value(forKey: "elements")
  let distance = elementArray[0].value(forKey: "distance")
  let text = distance.value(forKey: "text")
  print(text)
  let value = distance.value(forKey: "value")
  print(value)

相关内容

  • 没有找到相关文章

最新更新