2
我想我的JSON對象添加到的境界,但我一直被拋出此錯誤如何添加一個JSON字典境界與AlamofireObjectMapper
無法投類型的值「__NSCFDictionary」(0x10c52f178)爲' NSArray'(0x10c52eb88)。
在線for user in result as! [AnyObject] {
。這是我的JSON響應:
{
"name" : "Jonny Walker",
"api_token" : "qwertyuiop1234567890",
"profile_picture" : "http:default_profile_picture.jpg",
"id" : 10,
"email" : "[email protected]"
"username" : "jonny"
}
這是我的代碼:
import Foundation
import Alamofire
import SwiftyJSON
import RealmSwift
import ObjectMapper
import AlamofireObjectMapper
class Login {
init(userName: String, passWord: String) {
Data.sharedInstance.userName = userName
Data.sharedInstance.passWord = passWord
}
// call this method to login
func getRequest() {
let parameters = [
"username" : Data.sharedInstance.userName!,
"password" : Data.sharedInstance.passWord!,
]
Alamofire.request(.POST, Data.todoEndpoint, parameters: parameters)
.responseJSON { response in
if let result = response.result.value
{
let value = JSON(result)
do{
print(Realm.Configuration.defaultConfiguration.fileURL!)
let realm = try! Realm()
for user in result as! [AnyObject] {
try realm.write{
realm.add(user as! Object, update: true)
}
}
}
catch let err as NSError {
print("Error with realm: " + err.localizedDescription)
}
}
else
{
print("JSON data is nil.")
}
}
}
}
如何將其映射到一個單一的用戶對象? – noobdev
我不知道。我認爲你可以用'let user = User()'創建一個新用戶並設置字典中的屬性。例如:user.name = dict [「name」] as?串 – switchCTRL