当我在此处使用双重作用域时[[String: Any]]
jsonArray为空
如何使其正常工作?
我尝试使用[String: Any]
起作用,但是现在我不能使用[ 0 ]["aaData"]
(例如),它说“不能用索引下标'[String:Any]”类型的值类型为“ Int””。
func displayURL(){
let myURLAdress = "http://www.ucrf.gov.ua/wp-admin/admin-ajax.php?action=get_wdtable&table_id=1&sEcho=3&iColumns=10&sColumns=&iDisplayStart=0&iDisplayLength=-1&mDataProp_0=0&mDataProp_1=1&mDataProp_2=2&mDataProp_3=3&mDataProp_4=4&mDataProp_5=5&mDataProp_6=6&mDataProp_7=7&mDataProp_8=8&mDataProp_9=9&sSearch=&bRegex=false&sSearch_0=&bRegex_0=false&bSearchable_0=true&sSearch_1=&bRegex_1=false&bSearchable_1=true&sSearch_2=&bRegex_2=false&bSearchable_2=true&sSearch_3=&bRegex_3=false&bSearchable_3=true&sSearch_4=&bRegex_4=false&bSearchable_4=true&sSearch_5=&bRegex_5=false&bSearchable_5=true&sSearch_6=&bRegex_6=false&bSearchable_6=true&sSearch_7=&bRegex_7=false&bSearchable_7=true&sSearch_8=&bRegex_8=false&bSearchable_8=true&sSearch_9=LTE-2600&bRegex_9=false&bSearchable_9=true&sRangeSeparator=~&_=1545585236527"
let myURL = URL(string: myURLAdress)
let task = URLSession.shared.dataTask(with: myURL!) { (data, response, error) in
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription ?? "Response Error")
return }
do{
//here dataResponse received from a network request
let jsonResponse = try JSONSerialization.jsonObject(with:
dataResponse, options: [])
//print(jsonResponse)
guard let jsonArray = jsonResponse as? [[String: Any]] else {
return
}
print(jsonArray)
} catch let parsingError {
print("Error", parsingError)
}
}
task.resume()
}
}
答案 0 :(得分:1)
您需要
let jsonResponse = try JSONSerialization.jsonObject(with:dataResponse, options: []) as! [String:Any]
guard let jsonArray = jsonResponse["aaData"] as? [[String]] else {
return
}
您的json结构
{
"sEcho": 3,
"iTotalRecords": "174289",
"iTotalDisplayRecords": "1448",
"aaData": [[ "" ,"" , ""]]
}
顺便说一句总是推荐
struct Root : Codable {
let sEcho: Int
let iTotalRecords, iTotalDisplayRecords: String
let aaData: [[String]]
}
然后
let res = try JSONDecoder().decode(Root.self,from:data)
let arr = res.aaData