ObjectMapper 无法序列化响应
ObjectMapper failed to serialize response
我正在使用 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)
}
}
}
这是我的数据模型Class
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 时,这段代码工作正常。请帮忙!!
谢谢
您的代码没有问题,但是 URL 中的 JSON 格式错误。
第三个对象的温度字段为空。
我正在使用 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)
}
}
}
这是我的数据模型Class
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 时,这段代码工作正常。请帮忙!!
谢谢
您的代码没有问题,但是 URL 中的 JSON 格式错误。 第三个对象的温度字段为空。