首页 > 解决方案 > 使用 Alamofire 和 Swift 返回嵌套 JSON 数组中的值

问题描述

对 swift、JSON 和几乎所有编码来说都是超级新手,所以如果这个问题对网站上的其他人来说是多余的,或者我在这里遗漏了一些简单的东西,我提前道歉。

我希望在下面的 JSON 代码中的“元素”数组中返回与“距离”相关的“文本”(“1.7 英里”)的值:

{
   "destination_addresses" : [ "30 Rockefeller Plaza, New York, NY 10112, USA" ],
   "origin_addresses" : [ "352 7th Ave, New York, NY 10001, USA" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "1.7 mi",
                  "value" : 2729
               },
               "duration" : {
                  "text" : "15 mins",
                  "value" : 887
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

我使用 Alamofire 和 Google DistanceMatrix 检索了 JSON 数据(请参阅下面的代码),但是在解析数据以隔离我需要的内容时遇到了麻烦。我知道下面的代码并不接近我需要的,但不确定如何继续。

func distanceMatrix(startLocation: String, endLocation: String) {
        let myOrigin = startLocationTFText
        let myDestination = destinationLocationTFText

        let url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=\(myOrigin)&destinations=\(myDestination)&key=API_Key

        let encodedUrl = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

        AF.request(encodedUrl!).responseJSON { response in
            print(response.request as Any)
            print(response.response as Any)
            print(response.data as Any)
            print(response.result as Any)

            let json = JSON(response.data as Any)

任何帮助深表感谢。谢谢你。

标签: jsonswiftmultidimensional-arrayalamofireswifty-json

解决方案


您可以使用Decodable来获得所需的结果。

struct RootResponse: Decodable {

   let destinationAddresses, originAddresses: [String]
   let rows: [Rows]
   let status: String
}

struct Rows: Decodable {

  let elements: [Elements]
}

struct Elements: Decodable {

  let distance, duration: Details
  let status: String
}

struct Details: Decodable {
   let text, value: String
}

这将是您的模型文件,一旦您添加了它,您就可以返回到您的函数并将其用作:

func distanceMatrix(startLocation: String, endLocation: String) {
    let myOrigin = startLocationTFText
    let myDestination = destinationLocationTFText

    let url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=\(myOrigin)&destinations=\(myDestination)&key=API_Key"

    let encodedUrl = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

    AF.request(encodedUrl!).responseJSON { response in
        print(response.request as Any)
        print(response.response as Any)
        print(response.data as Any)
        print(response.result as Any)

        let decoder = JSONDecoder()
        decoder.keyDecodingStrategy = .convertFromSnakeCase

        guard let json = try? decoder.decode(RootResponse.self, from: response.data) else { print("Unable to parse JSON"); return }

        print(json)
        print(json.rows.first?.elements.first?.distance.value) // This is how you can get the value, but it will be better to safely unwrap them and I have also used first? to get the first object but this is an array and you can always use a for loop for further purpose
}

推荐阅读