从 'Array<JSON>'(又名 'Array<Dictionary<String, Any>>')转换为无关类型 'JSON'(又名 'Dictionary<String, Any>')总是失败
Cast from 'Array<JSON>' (aka 'Array<Dictionary<String, Any>>') to unrelated type 'JSON' (aka 'Dictionary<String, Any>') always fails
我正在尝试使用来自 JSON 的数据加载 table。我想将 JSON 反序列化为一个数组。我使用了一个名为 Gloss 的第三方库,反正应该很容易,但我无法解决警告(与该线程的标题相同)。
这是 JSON 数据:http://prntscr.com/d8zdb5(这是一个有效的 JSON,我已经使用 JSONLint 对其进行了检查)
这是我的代码片段:
初始化
import Gloss
...
class CourierViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
struct courierList: Decodable{
let shipper: String?
let service: String?
let cost: Int?
let etd: String?
init?(json: JSON){
self.shipper = "shipper" <~~ json
self.service = "service" <~~ json
self.cost = "cost" <~~ json
self.etd = "etd" <~~ json
}
}
var TableData:Array<JSON> = Array<JSON>()
...
}
从服务器下载JSON:
...
override func viewDidLoad() {
super.viewDidLoad()
get_data_from_url(url: "https://www.imperio.co.id/project/ecommerceApp/CourierDataReq.php")
}
...
func get_data_from_url(url:String){
self.TableData.removeAll(keepingCapacity: false)
let parameterURL = ["dest":User_city.text!,"weight":String(CartManager.sharedInstance.totalWeightInCart())]
Alamofire.request(url, parameters: parameterURL).validate(contentType: ["application/json"]).responseJSON{ response in
switch response.result{
case .success(let data):
self.TableData.append(data as! JSON)
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
})
break
case .failure(let error):
print("Error: \(error)")
break
}
}
}
使用数组加载table视图
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let value = TableData as? JSON, //the warning appears in here
let eventsArrayJSON = value["ShipperResult"] as? [JSON]
else { fatalError() }
let CourierList = [courierList].from(jsonArray: eventsArrayJSON)
print((CourierList?.count)!)
return (CourierList?.count)!
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CourierCell", for: indexPath) as! CourierTableViewCell
if indexPath.row % 2 == 0 {
cell.backgroundColor = UIColor(red: 200.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1.0)
} else {
cell.backgroundColor = UIColor(red: 135.0/255.0, green: 212.0/255.0, blue: 236.0/255.0, alpha: 1.0)
}
guard let value = TableData as? JSON, //The warning appears in here
let eventsArrayJSON = value["ShipperResult"] as? [JSON]
else { fatalError() }
let CourierList = [courierList].from(jsonArray: eventsArrayJSON)
for j in 0 ..< Int((CourierList?.count)!){
cell.label_shippingCourier.text = (CourierList?[j].shipper!)!
cell.label_shippingCourier.sizeToFit()
cell.label_serviceName.text = (CourierList?[j].service!)!
cell.label_serviceName.sizeToFit()
cell.label_estCost.text = String(describing: (CourierList?[j].cost!)!)
cell.label_estCost.sizeToFit()
if (CourierList?[j].etd! == "") {
cell.label_etd.text = "Data is not available"
} else {
cell.label_etd.text = (CourierList?[j].etd!)!
}
cell.label_etd.sizeToFit()
}
cell.selectionStyle = .none
return cell
}
知道如何解决这个问题吗?谢谢。
编辑:
我忘了说我用 Swift 3.
@vadian 非常感谢你帮助我,这是一个棘手的错误。
对于以某种方式也遇到此问题的任何人,答案是:
"Don't cast array to dictionary by any chance." 如果您需要创建一个空字典,请阅读此 post Swift: declare an empty dictionary
我正在尝试使用来自 JSON 的数据加载 table。我想将 JSON 反序列化为一个数组。我使用了一个名为 Gloss 的第三方库,反正应该很容易,但我无法解决警告(与该线程的标题相同)。
这是 JSON 数据:http://prntscr.com/d8zdb5(这是一个有效的 JSON,我已经使用 JSONLint 对其进行了检查)
这是我的代码片段: 初始化
import Gloss
...
class CourierViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
struct courierList: Decodable{
let shipper: String?
let service: String?
let cost: Int?
let etd: String?
init?(json: JSON){
self.shipper = "shipper" <~~ json
self.service = "service" <~~ json
self.cost = "cost" <~~ json
self.etd = "etd" <~~ json
}
}
var TableData:Array<JSON> = Array<JSON>()
...
}
从服务器下载JSON:
...
override func viewDidLoad() {
super.viewDidLoad()
get_data_from_url(url: "https://www.imperio.co.id/project/ecommerceApp/CourierDataReq.php")
}
...
func get_data_from_url(url:String){
self.TableData.removeAll(keepingCapacity: false)
let parameterURL = ["dest":User_city.text!,"weight":String(CartManager.sharedInstance.totalWeightInCart())]
Alamofire.request(url, parameters: parameterURL).validate(contentType: ["application/json"]).responseJSON{ response in
switch response.result{
case .success(let data):
self.TableData.append(data as! JSON)
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
})
break
case .failure(let error):
print("Error: \(error)")
break
}
}
}
使用数组加载table视图
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let value = TableData as? JSON, //the warning appears in here
let eventsArrayJSON = value["ShipperResult"] as? [JSON]
else { fatalError() }
let CourierList = [courierList].from(jsonArray: eventsArrayJSON)
print((CourierList?.count)!)
return (CourierList?.count)!
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CourierCell", for: indexPath) as! CourierTableViewCell
if indexPath.row % 2 == 0 {
cell.backgroundColor = UIColor(red: 200.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1.0)
} else {
cell.backgroundColor = UIColor(red: 135.0/255.0, green: 212.0/255.0, blue: 236.0/255.0, alpha: 1.0)
}
guard let value = TableData as? JSON, //The warning appears in here
let eventsArrayJSON = value["ShipperResult"] as? [JSON]
else { fatalError() }
let CourierList = [courierList].from(jsonArray: eventsArrayJSON)
for j in 0 ..< Int((CourierList?.count)!){
cell.label_shippingCourier.text = (CourierList?[j].shipper!)!
cell.label_shippingCourier.sizeToFit()
cell.label_serviceName.text = (CourierList?[j].service!)!
cell.label_serviceName.sizeToFit()
cell.label_estCost.text = String(describing: (CourierList?[j].cost!)!)
cell.label_estCost.sizeToFit()
if (CourierList?[j].etd! == "") {
cell.label_etd.text = "Data is not available"
} else {
cell.label_etd.text = (CourierList?[j].etd!)!
}
cell.label_etd.sizeToFit()
}
cell.selectionStyle = .none
return cell
}
知道如何解决这个问题吗?谢谢。
编辑: 我忘了说我用 Swift 3.
@vadian 非常感谢你帮助我,这是一个棘手的错误。
对于以某种方式也遇到此问题的任何人,答案是: "Don't cast array to dictionary by any chance." 如果您需要创建一个空字典,请阅读此 post Swift: declare an empty dictionary