【问题标题】:Cannot pass JSON array to array无法将 JSON 数组传递给数组
【发布时间】:2016-06-02 02:02:32
【问题描述】:

我正在尝试将我的 JSON 数组传递给一个名为 array 的数组,这样我就可以使用值为 27 的 submission_id 查询该数组以获得 safety_rating_id、schedule_job_id、score 和 @987654327 @来自这个 JSON https://codeshare.io/UqJMV 但我被抛出了这个错误

无法将类型“[JSON]”的值转换为预期的参数类型“JSON”

将 JSON 传递给数组的代码:

var array: [JSON] = []

func getTask(onCompletion: () -> (), onError: ((NSError) -> ())? = nil) {

     guard let endPoint = Data.sharedInstance.weeklyEndpoint 
else { print("Empty endpoint"); return }

    Alamofire.request(.GET, endPoint, encoding: .JSON)
        .validate()
        .responseJSON { response in

        switch response.result {

        case .Success:
            if let value = response.result.value {
                let json = JSON(value)
                for (_,subJson):(String, JSON) in json {
                    if let date = subJson["start_date"].string{
                        self.date = date
                    }
                    if let building = subJson["building_name"].string{
                        self.building = building
                    }
                    if let jobId = subJson["schedule_job_id"].int {
                        self.jobIdArray.append(jobId)
                    }

                    if let tasks = subJson["tasks"].array{
                        Tasks.sharedInstance.datas = tasks
                        for building in tasks {
                            if let ratings = building["safety_ratings"].array{
                                print(ratings)

                                self.array.append(ratings)

                            }
                        }
                    }


                }

                onCompletion()
            }

        case .Failure(let error):
            print("Request failed with error: \(error)")
            onError?(error)
        }
    }      
}

【问题讨论】:

    标签: arrays json swift2 swifty-json


    【解决方案1】:

    append() 需要单个元素 (JSON),但 ratings 是一个数组 ([JSON])。

    这就是错误消息的内容。

    要附加一个数组,请使用appendContentsOf:

    self.array.appendContentsOf(ratings)
    

    【讨论】:

    • 如何过滤包含submission_id = 27 的数组? (我想得到submission_id为27的两个字典)
    • let filteredArray = array.filter {$0["submission_id"] as! Int == 27}
    • 它让我从“JSON”转换为不相关类型“Int”总是失败
    • 您需要将JSON 数组转换为“普通”数组,可能是array.arrayValue.filter...
    猜你喜欢
    • 2018-01-18
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    • 2011-11-13
    • 1970-01-01
    • 2014-04-03
    • 2022-06-15
    • 2022-01-11
    相关资源
    最近更新 更多