如何将Any
类型I从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
}
但是编译器给了我错误信息:
'任何'不可转换为' [[AnyHashable:Any]]'
P.S。
我需要解析字典数组,所以JSON文件看起来像这样:
[{
"username": "admin",
"password": "123"
}, {
"username": "bbvb",
"password": "3333"
}, {
"username": "asd",
"password": "222"
}]
答案 0 :(得分:1)
为什么使用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
}