ObjectMapper无法序列化响应

时间:2016-09-19 15:50:34

标签: ios swift alamofire objectmapper

我正在使用AlamofireObjectMapper,只要响应包含任何空值,就会出现错误,

“FAILURE:Error Domain = com.alamofireobjectmapper.error Code = 2”ObjectMapper无法序列化响应。“UserInfo = {NSLocalizedFailureReason = ObjectMapper无法序列化响应。}”

这就是我要求的方式

let URL = "https://demo6336282.mockable.io/myapi"
        Alamofire.request(URL).validate().responseObject { (response: DataResponse<WeatherResponse>) in

            let weatherResponse = response.result.value
            print(weatherResponse?.location)

            if let threeDayForecast = weatherResponse?.threeDayForecast {
                for forecast in threeDayForecast {
                    print(forecast.day)
                    print(forecast.temperature)           
                }
            }
        }

这是我的DataModel类

import Foundation
import ObjectMapper
import AlamofireObjectMapper

class WeatherResponse: Mappable {
    var location: String? = ""
    var threeDayForecast: [Forecast]? = []

    required init?(map: Map){

    }

    func mapping(map: Map) {
        location <- map["location"]
        threeDayForecast <- map["three_day_forecast"]
    }
}

class Forecast: Mappable {
    var day: String? = ""
    var temperature: Int? = 0
    var conditions: String? = ""

    required init?(map: Map){

    }

    func mapping(map: Map) {
        day <- map["day"]
        temperature <- map["temperature"]
        conditions <- map["conditions"]
    }
}

我也尝试添加空白参数,因为这个api不需要参数,也添加了默认的URl编码但没有帮助。

我不知道我在哪里遗漏了什么,当api响应中没有任何null时,此代码可以正常工作。请帮忙!!

由于

1 个答案:

答案 0 :(得分:2)

您的代码没有问题,但网址中的JSON格式不正确。 第三个对象的温度字段为空。