在swift中将jsonparsing成一个数组
我是新的迅速,我得到一个请求json回来,但我不能parsing。 我正在尝试获取json信息并创build坐标以在注释上使用mapkit
下面是我回来的JSON
{ coord = [ { islocationactive = 1; latitude = "37.8037522"; locationid = 1; locationsubtitle = Danville; locationtitle = "Schreiner's Home"; longitude = "121.9871216"; }, { islocationactive = 1; latitude = "37.8191921"; locationid = 2; locationsubtitle = "Elementary School"; locationtitle = Montair; longitude = "-122.0071005"; }, { islocationactive = 1; latitude = "37.8186077"; locationid = 3; locationsubtitle = "Americas Eats"; locationtitle = "Chaus Restaurant"; longitude = "-121.999046"; }, { islocationactive = 1; latitude = "37.7789669"; locationid = 4; locationsubtitle = "Cheer & Dance"; locationtitle = Valley; longitude = "-121.9829908"; } ] }
我的代码试图parsing是这样的
let task = URLSession.shared.dataTask(with: request as URLRequest){ data, response, error in //exiting if there is some error if error != nil{ print("error is \(error)") return; } //parsing the response do { //converting resonse to NSDictionary var teamJSON: NSDictionary! teamJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary print(teamJSON) //getting the JSON array teams from the response let liquidLocations: NSArray = teamJSON["coord"] as! NSArray //looping through all the json objects in the array teams for i in 0 ..< liquidLocations.count{ //getting the data at each index // let teamId:Int = liquidLocations[i]["locationid"] as! Int! } } catch { print(error) } } //executing the task task.resume()
但不是我尝试的作品。 我想获取纬度,经度,并在地图上创build一个注释
谢谢您的帮助
你可以尝试下面的代码与@Niko Adrianus Yuwono相同,但做了一些改变,所以你会得到一个整数
do { let data : NSData = NSData() // change your data variable as you get from webservice response guard let teamJSON = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: Any], let liquidLocations = teamJSON["coord"] as? [[String: Any]] else { return } //looping through all the json objects in the array teams for i in 0 ..< liquidLocations.count{ let teamId: Int = (liquidLocations[i]["locationid"] as! NSString).integerValue print(teamId) } } catch { print(error) }
尝试这个
do { guard let teamJSON = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any], let liquidLocations = teamJSON["coord"] as? [[String: Any]] else { return } //looping through all the json objects in the array teams for i in 0 ..< liquidLocations.count{ let teamId: Int = (liquidLocations[i]["locationid"] as! NSString).integerValue } } catch { print(error) }
关键是不要使用NSDictionary和NSArray,因为它不是强types(虽然你可以使它强types)使用Swift的数组和字典,你可以使用[Element Type]
数组和字典[Key: Value]