我正在迅速使用AlamofireObjectMapper。但是我收到错误“ ObjectMapper无法序列化响应。” 。这是我的api响应和模型,请给我解决方案。作为响应,没有任何空值。
这是API响应
{"status":true,"result":[{"id":"246","sortname":"ZW","name":"Zimbabwe","phonecode":"263"},{"id":"245","sortname":"ZM","name":"Zambia","phonecode":"260"},{"id":"202","sortname":"ZA","name":"South Africa","phonecode":"27"},{"id":"244","sortname":"YU","name":"Yugoslavia","phonecode":"38"},{"id":"141","sortname":"YT","name":"Mayotte","phonecode":"269"},{"id":"243","sortname":"YE","name":"Yemen","phonecode":"967"},{"id":"91","sortname":"XU","name":"Guernsey and Alderney","phonecode":"44"}]}
这正在调用API
Alamofire.request(geturl, method: .get).responseArray { [weak self] (response: DataResponse<[countrymodel]>) in
print(response)
switch response.result {
case .success(let assignments):
let realm = try! Realm()
try! realm.write {
realm.delete(realm.objects(countrymodel.self))
realm.add(assignments, update: true)
}
for a in assignments{
print(a)
}
case .failure(let error):
print(".... . .. . .. . .")
}
}
这是我的Model课
import UIKit
import RealmSwift
import ObjectMapper
class countrymodel: Object, Mappable{
enum Status: Int, CustomStringConvertible {
case open, closed, cancelled
var description : String {
switch self {
case .open: return "Open"
case .closed: return "Closed"
case .cancelled: return "Cancelled"
}
}
}
@objc dynamic var id = 0
@objc dynamic var sortname = ""
@objc dynamic var name = ""
@objc dynamic var phonecode = ""
override static func primaryKey() -> String? {
return "id"
}
required convenience init?(map: Map) {
self.init()
}
func mapping(map: Map) {
id <- (map["id"])
sortname <- map["sortname"]
name <- map["name"]
phonecode <- map["phonecode"]
}
}
答案 0 :(得分:0)
您的响应不是一个数组,而是一个字典,并且内部有一个名为result
的数组,因此序列化失败,您可以使它
Alamofire.request(geturl, method: .get).responseJSON
并仅解析该数组
答案 1 :(得分:0)
您可以尝试以下代码: 更改此代码
params).responseArray(completionHandler: { (response: DataResponse<[countrymodel]>) in
像这样:
params).responseObject {(response: DataResponse<countrymodel>) in