在swift中解析谷歌地图api中的json数据

时间:2016-02-24 17:46:44

标签: json xcode swift api parsing

我正在使用google maps API解析JSON数据,以便使用经度和时间来获取我当前的位置城市。纬度。

但是现在我坚持使用我的代码,我无法访问结果中的数据。例如,我想在" administrative_area_level_2"中获取数据。关键"长名"。我怎样才能访问它?

dispatch_async(dispatch_get_main_queue(), {

            if let urlContent = data{
                do{
                    let jsonResult = try NSJSONSerialization.JSONObjectWithData(urlContent, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
                    if let results = jsonResult["results"] as? [[String : AnyObject]] {

                        for result in results{

                            if let addressComponents = result["address_components"] as? [[String : AnyObject]] {

                                print(addressComponents)
                            }
                        }
                    }
                  //  print(jsonResult)

                } catch{

                }

            }

        })

以下是控制台中的addressComponents JSON结果:

    [["types": (
    route
), "short_name": Abou Al MAGD Al Askalani, "long_name": Abou Al MAGD Al Askalani], ["types": (
    "administrative_area_level_3",
    political
), "short_name": Al Golf, "long_name": Al Golf], ["types": (
    "administrative_area_level_2",
    political
), "short_name": Nasr City, "long_name": Nasr City], ["types": (
    "administrative_area_level_1",
    political
), "short_name": Cairo Governorate, "long_name": Cairo Governorate], ["types": (
    country,
    political
), "short_name": EG, "long_name": Egypt]]

以下是控制台中jsonResult结果的结果:

results =     (
            {
        "address_components" =             (
                            {
                "long_name" = "Abou Al MAGD Al Askalani";
                "short_name" = "Abou Al MAGD Al Askalani";
                types =                     (
                    route
                );
            },
                            {
                "long_name" = "Al Golf";
                "short_name" = "Al Golf";
                types =                     (
                    "administrative_area_level_3",
                    political
                );
            },
                            {
                "long_name" = "Nasr City";
                "short_name" = "Nasr City";
                types =                     (
                    "administrative_area_level_2",
                    political
                );
            },
                            {
                "long_name" = "Cairo Governorate";
                "short_name" = "Cairo Governorate";
                types =                     (
                    "administrative_area_level_1",
                    political
                );
            },
                            {
                "long_name" = Egypt;
                "short_name" = EG;
                types =                     (
                    country,
                    political
                );
            }
        );

3 个答案:

答案 0 :(得分:2)

对于深度嵌套的JSON,我建议使用像SwiftyJSON这样的第三方库,但这是一个“无”解决方案。它使用filter函数来获取包含所请求的type

的项目
if let urlContent = data {
  do {
    let jsonResult = try NSJSONSerialization.JSONObjectWithData(urlContent, options: NSJSONReadingOptions()) as! [String : AnyObject]

    if let results = jsonResult["results"] as? [[String : AnyObject]] {
      for result in results{
        if let addressComponents = result["address_components"] as? [[String : AnyObject]] {

          let filteredItems = addressComponents.filter{ if let types = $0["types"] as? [String] {
            return types.contains("administrative_area_level_2") } else { return false } }
          if !filteredItems.isEmpty {
             print(filteredItems[0]["long_name"] as! String)
          }
        }
      }
    }
  } catch let error as NSError {
    print(error)
  }
}

答案 1 :(得分:0)

在我的某个应用中,我正在使用placeID加载有关地点的详细信息。但是,结果将以与您相同的格式返回。这是一个可能对您有帮助的代码段:

let task = NSURLSession.sharedSession().dataTaskWithURL(url) {(data, _, retError) in
if let error = retError {
    self.error = .RequestError(error)
    return
}
guard
    let JSON = data else {
        self.error = .CannotParseData
        return
}
do {
    let json = try NSJSONSerialization.JSONObjectWithData(JSON, options: .MutableContainers)
    guard
        let results = json["results"] as? [[String: AnyObject]]
        else {
            self.error = .CannotParseData
            return
    }
    if results.count == 0 {
        self.error = .NoResults
        return
    }

    let result = results[0]
    // first check that locality exists
    guard let resultTypes = result["types"] as? [String],
        let addressComponents = result["address_components"] as? [[String:AnyObject]],
        let formattedAddress = result["formatted_address"] as? String,
        let geometry = result["geometry"] as? [String:AnyObject],
        let location = geometry["location"] as? [String:Double],
        let lat = location["lat"],
        let lng = location["lng"]
        else {
            //let error = NSError()
            self.error = .CannotParseData
            return
        }
        // at this point you can use all the variables declared above
    }
}

我希望这有用。

答案 2 :(得分:0)

func calculateDistanceByGoogleAPI(){
    let currentLat = 48.855683 //self.currentLocation.latitude
    let currentLon = 2.353580 //self.currentLocation.longitude
    let restLat = self.restaurantObj.location.coordinate.latitude
    let restLon = self.restaurantObj.location.coordinate.longitude

    let url = "https://maps.googleapis.com/maps/api/distancematrix/json?&origins=\(currentLat),\(currentLon)&destinations=\(restLat),\(restLon)&key=\(Constants.GMAP_KEY)"

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

    let header: HTTPHeaders = [ "Accept": "application/json", "Content-Type": "application/json" ]

    AF.request(encodedUrl! , method: .get,encoding: JSONEncoding.default, headers: header)
        .responseJSON { (response) in
            if let result = response.result.value {
                let json = JSON(result) //use SwiftyJSON pod and import
                let distanceStr = json["rows"][0]["elements"][0]["distance"]["text"].string
                self.distanceLbl.text = distanceStr
            }

    }
}
  

使用SwiftyJSON之类的JSON库并像​​这样读取gooogle api响应