ios – 在swift 3中将json解析为数组

前端之家收集整理的这篇文章主要介绍了ios – 在swift 3中将json解析为数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是 swift的新手,我从请求中得到一个json,但我无法解析.我正在尝试获取json信息并创建在mapkit上使用注释的坐标

下面是我回来的json

  1. {
  2. coord = [
  3. {
  4. islocationactive = 1;
  5. latitude = "37.8037522";
  6. locationid = 1;
  7. locationsubtitle = Danville;
  8. locationtitle = "Schreiner's Home";
  9. longitude = "121.9871216";
  10. },{
  11. islocationactive = 1;
  12. latitude = "37.8191921";
  13. locationid = 2;
  14. locationsubtitle = "Elementary School";
  15. locationtitle = Montair;
  16. longitude = "-122.0071005";
  17. },{
  18. islocationactive = 1;
  19. latitude = "37.8186077";
  20. locationid = 3;
  21. locationsubtitle = "Americas Eats";
  22. locationtitle = "Chaus Restaurant";
  23. longitude = "-121.999046";
  24. },{
  25. islocationactive = 1;
  26. latitude = "37.7789669";
  27. locationid = 4;
  28. locationsubtitle = "Cheer & Dance";
  29. locationtitle = Valley;
  30. longitude = "-121.9829908";
  31. }
  32. ] }

我尝试解析的代码就是这个

  1. let task = URLSession.shared.dataTask(with: request as URLRequest){
  2. data,response,error in
  3.  
  4. //exiting if there is some error
  5. if error != nil{
  6. print("error is \(error)")
  7. return;
  8. }
  9.  
  10. //parsing the response
  11. do {
  12. //converting resonse to NSDictionary
  13. var teamJSON: NSDictionary!
  14.  
  15. teamJSON = try JSONSerialization.jsonObject(with: data!,options: .mutableContainers) as? NSDictionary
  16. print(teamJSON)
  17. //getting the JSON array teams from the response
  18. let liquidLocations: NSArray = teamJSON["coord"] as! NSArray
  19.  
  20. //looping through all the json objects in the array teams
  21. for i in 0 ..< liquidLocations.count{
  22.  
  23. //getting the data at each index
  24. // let teamId:Int = liquidLocations[i]["locationid"] as! Int!
  25.  
  26. }
  27.  
  28. } catch {
  29. print(error)
  30. }
  31. }
  32. //executing the task
  33. task.resume()

但不是我尝试工作.我想得到纬度,经度并在地图上创建一个注释

谢谢您的帮助

解决方法

您可以尝试使用与@Niko Adrianus Yuwono相同的代码,但进行了一些更改,因此您将获得teamid作为整数
  1. do {
  2. let data : NSData = NSData() // change your data variable as you get from webservice response
  3. guard let teamJSON = try NSJSONSerialization.JSONObjectWithData(data,options: []) as? [String: Any],let liquidLocations = teamJSON["coord"] as? [[String: Any]]
  4. else { return }
  5.  
  6. //looping through all the json objects in the array teams
  7. for i in 0 ..< liquidLocations.count{
  8. let teamId: Int = (liquidLocations[i]["locationid"] as! NSString).integerValue
  9. print(teamId)
  10. }
  11.  
  12. } catch {
  13. print(error)
  14. }

猜你在找的iOS相关文章