在swift解析谷歌的地方json

时间:2014-11-18 01:15:54

标签: json parsing swift

我不明白如何解决这个棘手的问题...

我试图解析一些来自Google地方电话的json。

这是代码中有趣的部分:

// Sending Asynchronous request using NSURLConnection
        NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{(response:NSURLResponse!, responseData:NSData!, error: NSError!)->Void in

            if error != nil
            {
                println(error.description)
                println("Couldn't reach api")
            }
            else
            {
                //Converting data to String
                var responseDict: NSDictionary = NSJSONSerialization.JSONObjectWithData(responseData,options: NSJSONReadingOptions.MutableContainers, error:nil) as NSDictionary
                println("SUCCESS")
                var results:NSArray = responseDict["results"] as NSArray
                var item:NSDictionary = results[0] as NSDictionary
                self.googleAddress = item["formatted_address"] as NSString

                println("accessing geometry")
                let googleGeo:NSArray = item["geometry"] as NSArray
                println("accessing location")
                let googleLoc:NSDictionary = googleGeo[0] as NSDictionary
                        println("grabbing lat")
                        self.googleLatitude = googleLoc["lat"] as NSString
                        println("grabbing lng")
                        self.googleLongitude = googleLoc["lng"] as NSString
                println(self.googleLatitude)

项看起来像这样:

"formatted_address" : "5035 Rue Saint-Denis, Montréal, Québec H2J 2L8, Canada",
         "geometry" : {
            "location" : {
               "lat" : 45.526682,
               "lng" : -73.588599
            }
         },
         "icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/cafe-71.png",
         "id" : "11b53fd7721df9a1becb825ab8df3e91d8985624",
         "name" : "La Petite Marche",
         "opening_hours" : {
            "open_now" : true,
            "weekday_text" : []
         },
         "photos" : [
            {
               "height" : 960,
               "html_attributions" : [
                  "\u003ca href=\"https://plus.google.com/110862802692218089410\"\u003eÉric Paris\u003c/a\u003e"
               ],
               "photo_reference" : "CnRoAAAAHPehKz876gJCu1lmLr-hJkFYGgGKeGKzwbjiAYYFt3INTfN1fLUwEWG4WK5g4qWf9bL1GjxWTI4saFh2pYFYOMgZymVFRRwZGcuqzNTNMnzeZw_HS_fhXkkdQje7P3jS-n69c0L-agGyAIVpjMSTqBIQNgTb589QgVo135Ycvoy1choUKv7swtNzbdrDNJayJEqM8-I6sjA",
               "width" : 1280
            }
         ],
         "place_id" : "ChIJi-DyptcbyUwRiWA4C6Bjrf0",
         "rating" : 3.5,
         "reference" : "CoQBcwAAAIXlYOLFA_7Puiw4TYEt2GuMQAY9K2tykoBCEwjqVNIREoBwC9awyriE2zfe3vHzjKpHEXs_8Vdq3Ca0-nVR84lA-GubyXh-IDYAb9zZZE7bPi3TNVlNhjrLMRyLDMEOJdZEekkaFK51Kir0ZZ_-E-bx8ErrtV--eplGnmcV9GmtEhCfDLFPRnUSTHrPzY_pHqrdGhSMLgdiCK6iGAqEAT55jdk9vx31wg",
         "types" : [ "cafe", "restaurant", "food", "establishment" ]

正如您在我的代码中看到的,我想从json访问lat和lng值。

不幸的是,我无法找到一种方法来访问它并且应用程序崩溃在第一行:

let googleGeo:NSArray = item["geometry"] as NSArray

有人可以解释如何解析json在Swift中的工作原理吗?我想避免使用外部库(用于学习目的)

谢谢!

1 个答案:

答案 0 :(得分:3)

let googleGeo:NSArray = item["geometry"] as NSArray

问题在于,当它实际上是另一个字典时(至少根据您发布的JSON),您将geometry作为数组进行投射。相反,你应该这样做:

let googleGeo = item["geometry"] as NSDictionary
let googleLoc = googleGeo["location"] as NSDictionary
let latitude = googleLoc["lat"] as Float
let longitude = googleLoc["long"] as Float