使用Swift访问JSON

时间:2016-03-05 11:45:32

标签: ios json swift

我目前正在开发一款应用,我想显示一些特定地点的信息。我正在使用Google Places API执行此操作,并尝试从此JSON响应中提取一些信息:

{
"html_attributions": [],
"result": {
"address_components": [],
"adr_address": "5, \u003cspan class=\"street-address\"\u003e48 Pirrama Rd\u003c/span\u003e, \u003cspan class=\"locality\"\u003ePyrmont\u003c/span\u003e \u003cspan class=\"region\"\u003eNSW\u003c/span\u003e \u003cspan class=\"postal-code\"\u003e2009\u003c/span\u003e, \u003cspan class=\"country-name\"\u003eAustralia\u003c/span\u003e",
"formatted_address": "5, 48 Pirrama Rd, Pyrmont NSW 2009, Australia",
"formatted_phone_number": "(02) 9374 4000",
"geometry": {},
"icon": "https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id": "4f89212bf76dde31f092cfc14d7506555d85b5c7",
"international_phone_number": "+61 2 9374 4000",
"name": "Google",
"photos": [],
"place_id": "ChIJN1t_tDeuEmsRUsoyG83frY4",
"rating": 4.5,
"reference": "CmRaAAAAVvEJLOszIgZMqrn59xg_wEmLJUpC52Zd7HZzzcv0OsaRobY_f8galxBVNsyEgC9nhUsI7BQQcTYCA0t_f8JlhEV-dftt-OhapkRRvQ12g6R3FU-d6OWB-T1vYVIcRuEBEhBha4swICH7pUUsjBRivnHTGhT1Y97NAmr0iWe4qffGJH0iY96GKg",
"reviews": [],
"scope": "GOOGLE",
"types": [
  "point_of_interest",
  "establishment"
],
"url": "https://maps.google.com/?cid=10281119596374313554",
"user_ratings_total": 133,
"utc_offset": 660,
"vicinity": "5 48 Pirrama Road, Pyrmont",
"website": "https://www.google.com.au/about/careers/locations/sydney/"
},
"status": "OK"
}

我在视图控制器中使用的代码是:

let reposURL = NSURL(string: "https://maps.googleapis.com/maps/api/place/details/json?placeid=\(chosenPlaceID!)&key=SOMEAPIKEY")!

    if let JSONData = NSData(contentsOfURL: reposURL) {

        if let json = (try? NSJSONSerialization.JSONObjectWithData(JSONData, options: [])) as? NSDictionary {

            if let reposArray = json["result"] as? [NSDictionary] {

                for item in reposArray {
                    placeRepositories.append(PlaceRepository(json: item ))
                }

            }
        }
    }

我的placeRepository控制器中的代码是:

class PlaceRepository {

var name: String?
var formattedAddress: String?
var formattedPhoneNumber: String?
var internationPhoneNumber: String?
var types: [String]?

init(json: NSDictionary) {
    self.name = json["name"] as? String
    self.formattedAddress = json["formatted_address"] as? String
    self.formattedPhoneNumber = json["formatted_phone_number"] as? String
    self.internationPhoneNumber = json["international_phone_number"] as? String
    self.types = json["types"] as? [String]

    }
}

I have put a breakpoint in to try and find out what is going on and the for item in reposArray code is never accessed, it gets skipped over in the previous if statement but I am not sure why? 非常感谢任何帮助。

谢谢。

2 个答案:

答案 0 :(得分:0)

您的回复表明json ["结果"]不是字典数组... [NSDictionary] ...其NSDictionary

更改此行

if let reposArray = json["result"] as? [NSDictionary] { ... }

if let reposArray = json["result"] as? NSDictionary {
      PlaceRepository(json: reposArray )
}   
  

之后你就不能像NS一样循环NSDictionary         for item in reposArray { .. }

答案 1 :(得分:0)

您可以使用第三方库,例如SwiftyJson它可以让JSON解析变得更加轻松。