2016-05-23 39 views
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.") 
} 

} 

} 

} 

回答

2

看來你只能得到一個用戶,而不是多個。在這種情況下,您應該嘗試解析您對陣列的響應,如果失敗,請嘗試將其映射到單個用戶對象...

不要使用「as!」。用於?」相反,並測試爲零。

例子:

let dict = response as? Dictionary<String, AnyObject> 

if dict != nil { 
    // Parse a single User 
} else { 
    let arr = response as? [AnyObject] 
} 
+0

如何將其映射到一個單一的用戶對象? – noobdev

+0

我不知道。我認爲你可以用'let user = User()'創建一個新用戶並設置字典中的屬性。例如:user.name = dict [「name」] as?串 – switchCTRL