【问题标题】:parsing json into an array in swift 3在swift 3中将json解析为数组
【发布时间】:2017-02-07 04:06:38
【问题描述】:

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

但不是我尝试的作品。我想获取纬度、经度并在地图上创建注释

感谢您的帮助

【问题讨论】:

  • 你需要告诉我们更多关于出了什么问题。
  • 就用这段代码让teamId:Int =liquidLocations[i]["locationid"] as!诠释!它抛出这个错误:类型“Any”没有下标成员

标签: ios json swift3


【解决方案1】:

试试这个

        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,因为它不是强类型的(虽然你也可以使它成为强类型)使用 Swift 的数组和字典,你可以使用 [Element Type] 用于数组,[Key: Value] 用于字典

【讨论】:

  • 嗨 Niko,当我运行代码时,我得到了无法将类型“NSTaggedPointerString”(0x1027f1b90)的值转换为“NSNumber”(0x101dfa300)。在这一行中让 teamId: Int = liquidLocations[i]["locationid"] as!诠释!
  • @RodrigoSchreiner 看起来在 Swift 3 中 id 被翻译为 Any 而不是 AnyObject,你能测试我更新的答案吗?
  • 嗨 Niko,我刚刚测试了更新的版本,现在我得到了它无法将类型“NSTaggedPointerString”(0x10aef7b90)的值转换为“NSNumber”
  • @RodrigoSchreiner 好的,那么我关于 JSONSerialization 将值映射到 NSString 的假设似乎是正确的,再次尝试更新的答案,我先转换为 NSString 然后获取 integerValue
【解决方案2】:

您可以尝试使用与@Niko Adrianus Yuwono 相同的以下代码,但进行了一些更改,以便您将teamid 设为整数

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多