在Swift 3中将JSON解析为数组

6

我是新手,正在学习Swift编程语言。我发出一个请求后得到了一个JSON响应,但是我无法解析它。我想要获取JSON数据并创建坐标点,以便在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";
        }
    ] }

我尝试解析的代码如下

 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()

但我尝试了并没有成功。我想获取纬度、经度并在地图上创建一个标注。

感谢您的帮助。


你需要告诉我们更多关于出了什么问题。 - Graham Perks
在这行代码中:let teamId:Int = liquidLocations[i]["locationid"] as! Int!,它会抛出以下错误:类型“Any”没有下标成员。 - Rodrigo Schreiner
2个回答

8
你可以尝试下面的代码,它与@Niko Adrianus Yuwono的代码相同,但进行了一些更改,因此你将得到一个整数作为团队ID。
    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)
    }

2

试试这个

        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,因为它们没有强类型(虽然你也可以使其强类型化)。在可以使用[Element Type]作为数组和[Key: Value]作为字典的情况下,请使用Swift的数组和字典。


嗨,尼科,当我运行代码时,我得到了这个错误:在这一行中无法将类型为“NSTaggedPointerString”(0x1027f1b90)的值转换为“NSNumber”(0x101dfa300)。let teamId: Int = liquidLocations[i]["locationid"] as! Int! - Rodrigo Schreiner
@RodrigoSchreiner 看起来在Swift 3中,id被翻译成了Any而不是AnyObject,你能测试一下我的更新答案吗? - Niko Adrianus Yuwono
嗨Niko,我刚测试了更新版本,现在出现了这个问题:无法将类型为'NSTaggedPointerString' (0x10aef7b90)的值转换为'NSNumber'。 - Rodrigo Schreiner
1
@RodrigoSchreiner 好的,那么我对JSONSerialization将值映射到NSString的假设是正确的。请再尝试更新后的答案,其中我首先将其转换为NSString,然后获取integerValue。 - Niko Adrianus Yuwono

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接