SwiftyJson无法设置值

3
我正在使用Alamofire获取卡车表格。SwiftyJSON用于处理结果。其中一列是每辆卡车的坐标。
我想将卡车坐标与用户当前位置进行比较。我已经可以进行计算。我考虑添加计算出的距离作为新字段到同一个JSONObject中,以便按距离排序,但我似乎无法设置新值。
设置json对象根本不起作用。以下是我的代码。我在它不起作用的部分进行了注释。我没有收到警告或错误。如果我打印出来,我只会得到一个空行。请帮忙。谢谢您的提前帮助。我这样做对吗?有什么建议可以让我更好地根据结果中的卡车坐标和设备上的用户位置按距离对列表进行排序吗?
 Alamofire.request(.POST, Ftf.endPoint(), parameters: params).responseJSON { response in

        if response.result.value != nil{
            let obj = JSON(response.result.value!)
            self.jsonObj = obj
            //ATTEMPT TO SORT THE JSON OBJECT
            print("Begin Sorting Object")
            print("User located at \(self.MyLocation)")

            for (key,subJson):(String, JSON) in self.jsonObj {
                let truckloc = subJson["truckLocation"].stringValue
                print("This truck is at \(truckloc)")

                let coords = truckloc
                var coord = coords.componentsSeparatedByString(",")
                let lat = coord[0]
                let lon = coord[1]
                let truckLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake((lat as NSString).doubleValue, (lon as NSString).doubleValue)
                let point1 = MKMapPointForCoordinate(self.MyLocation)
                let point2 = MKMapPointForCoordinate(truckLocation)
                let distance = MKMetersBetweenMapPoints(point1, point2)/1000
                let distanceStr = NSString(format: "%.1f", distance)

                print("Distance of truck from user is \(distanceStr)")

                //THIS LINE HERE DOESNT WORK. NO ERROR NO WARNINGS. JUST NOTHING HAPPENS
                self.jsonObj[key]["distance"].string = "\(distanceStr)"


            }

            self.activityIndicator.stopAnimating()
            self.tableView.reloadData()
            self.ftfRefresh.endRefreshing()
        }else{
            self.presentViewController(Ftf.generalAlert("No network connection found"), animated: true, completion: nil)
        }


    }

1
你尝试过 self.jsonObj[key]["distance"] = "\(distanceStr)" 吗? - sbarow
是的。如果我这样做,会得到一个“无法将类型为'String'的值分配给类型为'JSON'”。没有起作用。 - VBaarathi
1
也许可以这样写:self.jsonObj[key]["distance"] as! String = "\(distanceStr)" - Peter Tretyakov
2个回答

4

试试这个:

self.jsonObj[key]["distance"] = JSON("\(distanceStr)")

示例示范:

    var json = JSON(["1":"2"])

    print(json)

    json["1"] = JSON("3")

    print(json)

它说无法使用类型为“JSON”的初始化程序调用类型为“(String)”的参数列表。 - VBaarathi

0

我还没有想明白为什么,但似乎我解决了我的问题。我使用本地的对象而不是self.jsonObj,并添加了字段。完成后,我更新了全局的self.jsonObj。以下代码有效。另外,键被传递为字符串。我将其更改为整数。

 Alamofire.request(.POST, Ftf.endPoint(), parameters: params).responseJSON { response in

        if response.result.value != nil{
            var obj = JSON(response.result.value!)
                            //ATTEMPT TO SORT THE JSON OBJECT
            print("Begin Sorting Object")
            print("User located at \(self.MyLocation)")

            for (key,subJson):(String, JSON) in obj {
                let truckloc = subJson["truckLocation"].stringValue
                print("This truck is at \(truckloc)")

                let coords = truckloc
                var coord = coords.componentsSeparatedByString(",")
                let lat = coord[0]
                let lon = coord[1]
                let truckLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake((lat as NSString).doubleValue, (lon as NSString).doubleValue)
                let point1 = MKMapPointForCoordinate(self.MyLocation)
                let point2 = MKMapPointForCoordinate(truckLocation)
                let distance = MKMetersBetweenMapPoints(point1, point2)/1000
                let distanceStr = NSString(format: "%.1f", distance)

                print("Distance of truck from user is \(distanceStr)")

                //FINALLY IT WORKED

                obj[Int(key)!]["dist"].stringValue = distanceStr as String
                print(obj[Int(key)!]["dist"].stringValue)


            }

            self.jsonObj = obj



            self.activityIndicator.stopAnimating()
            self.tableView.reloadData()
            self.ftfRefresh.endRefreshing()
        }else{
            self.presentViewController(Ftf.generalAlert("No network connection found"), animated: true, completion: nil)
        }




    }

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