如何将从Any获得的JSONSerialization类型转换为字典数组?我的代码是:
let jsonArray: [[AnyHashable: Any]]
do {
jsonArray = try JSONSerialization.jsonObject(with: jsonData, options: [.ReadingOptions.allowFragments]) as! [[AnyHashable : Any]]
}
catch {
let description = NSLocalizedString("Could not analyze earthquake data", comment: "Failed to unpack JSON")
print(description)
return
}但是编译器给了我错误信息:
“Any”不可转换为“[AnyHashable:Any]”
附注:
我需要解析字典数组,因此JSON文件如下所示:
[{
"username": "admin",
"password": "123"
}, {
"username": "bbvb",
"password": "3333"
}, {
"username": "asd",
"password": "222"
}]发布于 2017-08-10 16:02:10
你为什么要用AnyHashable ??
试试这个:
let jsonArray: Any? = nil
do {
jsonArray = try JSONSerialization.jsonObject(with: jsonData, options: []) as! [Any]
if jsonArray != nil {
if let resp = jsonArray as? [[AnyHashable : Any]]{
//your result should be here inside resp, which is an array of dictionary of key-val type `AnyHashable : Any`, although you could just use String value for the key, making your format from [[AnyHashable : Any]] to [[String : Any]]
}
}
catch {
let description = NSLocalizedString("Could not analyze earthquake data", comment: "Failed to unpack JSON")
print(description)
return
}https://stackoverflow.com/questions/45618285
复制相似问题