我正在使用Alamofire
进行GET请求 - 它给我状态代码200并且结果很好,但是在我将json反序列化到数组中之后我尝试将值签名到自定义对象中然后它永远给我0。
json看起来像:
{
"user" : [
{
"name" : "Jack",
"lastname" : Sparrow
},
{
"name" : "John",
"lastname" : Smith
}
],
"count" : 2
}
然后在我的模型中,我确实拥有属性name
和lastname
init(name: String, lastname: String) { self.name = name self.lastname = lastname }
GET
请求如下:
Alamofire.request(BREADCRAMB_URL, method: .get, parameters: parameters).responseJSON { response in
print("Get default graph request \(response.request!)")
print("Get default graph response \(response.response!)")
guard response.result.value != nil else {
completion(nil, 0)
return
}
var objects: [User] = []
let jsonArray = JSON(data: response.data!)
let count = jsonArray["count"].intValue
print(jsonArray.count)
for(_ , dict) in jsonArray {
print(dict.count)
let thisObject = User.init(name: dict["name"].stringValue, lastname: dict["lastname"].stringValue)
print(thisObject)
objects.append(thisObject)
}
completion(objects, count)
print(objects.count)
for o in objects {
print(o.name)
print(o.lastname)
}
}
提前致谢!
答案 0 :(得分:0)
使用AlamofireObjectMapper库。它可以很容易地映射对象。
//在ViewController内部
var objects = [User]()
var serverResponse : ServerResponce
private func downloadMainViewData(){
let params = ["":""]
Alamofire.request(serverUrl, method: .get, parameters: params, encoding: JSONEncoding.default, headers: nil)
.responseObject{ (response: DataResponse<ServerResponse>) in
self.serverResponse = response.result.value
if(self.serverResponse != nil){
self.objects = (response.result.value?.slideShow)!
}
}
}
// Class ServerResponce
import ObjectMapper
class ServerResponse : Mappable{
var slideShow : [Show]?
required init?(map: Map) {
}
func mapping(map: Map) {
objects <- map["user"]
}
}
//班级用户
import ObjectMapper
class Uesr: Mappable{
var name : String?
var lastName : String?
required init(map: Map){
}
func mapping(map: Map) {
let transform = TransformOf<Int, String>(fromJSON: { (value: String?) -> Int? in
// transform value from String? to Int?
return Int(value!)
}, toJSON: { (value: Int?) -> String? in
// transform value from Int? to String?
if let value = value {
return String(value)
}
return nil
})
name <- map["name"]
lastName <- map["lastname"]
}
}