如何使用AlamofireObjectMapper将JSON字典添加到域中

时间:2016-05-23 06:01:30

标签: json swift2 realm alamofire

我正在尝试将我的JSON对象添加到Realm,但我不断抛出此错误

  

无法将“__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" : "jwalker@gmail.com"
  "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.")
}

}

}

}

1 个答案:

答案 0 :(得分:2)

您似乎只收到一个用户而非许多用户。在这种情况下,您应该尝试解析对数组的响应,如果失败,请尝试将其映射到单个用户对象...

不要使用“as!”。用于?”相反,测试为零。

示例:

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

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