JSON swift 3 从数组到字典的解析问题
JSON Parsing issue in swift 3 from Array to dictionary
我有一个 JSON 作为:
{
"jsonData": {
"userDetails": [
{
"user_id": "a",
"first_name": "First1",
"last_name": "Last1",
"donation_amount": 841,
"donation_time": 1452678347523
},
{
"user_id": "b",
"first_name": "First2",
"last_name": "Last2",
"donation_amount": 841,
"donation_time": 1452678347523
},
{
"user_id": "c",
"first_name": "First3",
"last_name": "Last3",
"donation_amount": 841,
"donation_time": 1452678347523
}
]
},
"total_count": 3
}
并且我在 swift 中使用 swiftlyJSON 进行解析:我的代码如下
private func processProjectDonorsResponse(response: JSON) {
//add to dictionary
let jsonObject = response.dictionaryObject!["jsonData"]! as AnyObject
let details = jsonObject["userDetails"] as! [AnyObject]
var tempModel = [UserModel]()
for detail in details {
let user = UserModel(response: detail as! [String: AnyObject])
tempModel.append(user)
}
}
它在 swift 2 中工作正常,但现在我已经升级到 swift 3 我在第 //let details = jsonObject["userDetails"] as! [AnyObject]
行收到警告
as: 从字符串中转换?!到不相关的类型 '[AnyObject]' 总是失败,并崩溃。
如何解决这个问题?
您的代码中的问题在以下行中:
let jsonObject = response.dictionaryObject!["jsonData"]! as AnyObject
只需将此代码更改为以下内容:
let jsonObject = response.dictionaryObject!["jsonData"]! as! [String: AnyObject]
希望这对你有用。
我有一个 JSON 作为:
{
"jsonData": {
"userDetails": [
{
"user_id": "a",
"first_name": "First1",
"last_name": "Last1",
"donation_amount": 841,
"donation_time": 1452678347523
},
{
"user_id": "b",
"first_name": "First2",
"last_name": "Last2",
"donation_amount": 841,
"donation_time": 1452678347523
},
{
"user_id": "c",
"first_name": "First3",
"last_name": "Last3",
"donation_amount": 841,
"donation_time": 1452678347523
}
]
},
"total_count": 3
}
并且我在 swift 中使用 swiftlyJSON 进行解析:我的代码如下
private func processProjectDonorsResponse(response: JSON) {
//add to dictionary
let jsonObject = response.dictionaryObject!["jsonData"]! as AnyObject
let details = jsonObject["userDetails"] as! [AnyObject]
var tempModel = [UserModel]()
for detail in details {
let user = UserModel(response: detail as! [String: AnyObject])
tempModel.append(user)
}
}
它在 swift 2 中工作正常,但现在我已经升级到 swift 3 我在第 //let details = jsonObject["userDetails"] as! [AnyObject]
行收到警告
as: 从字符串中转换?!到不相关的类型 '[AnyObject]' 总是失败,并崩溃。
如何解决这个问题?
您的代码中的问题在以下行中:
let jsonObject = response.dictionaryObject!["jsonData"]! as AnyObject
只需将此代码更改为以下内容:
let jsonObject = response.dictionaryObject!["jsonData"]! as! [String: AnyObject]
希望这对你有用。