【问题标题】:ObjectMapper failed to serialize responseObjectMapper 无法序列化响应
【发布时间】:2017-01-27 09:08:07
【问题描述】:

我正在使用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)           
                }
            }
        }

这是我的数据模型类

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 时,此代码可以正常工作。请帮忙!!

谢谢

【问题讨论】:

    标签: ios swift alamofire objectmapper


    【解决方案1】:

    您的代码没有问题,但 URL 中的 JSON 格式错误。 第三个物体的温度场是空的。

    【讨论】:

    • 这是我的问题,为什么当响应中有空值时它不序列化响应,因为可能存在我可能得到空响应的情况,那时我的代码应该替换它具有空值的 null。
    • 我只是想知道是否有任何方法可以让它用各自的默认值替换空值。
    • 我明白你的意思,但是 json 格式错误,并且在数组的第三个元素的温度字段中不是空值。
    • 谢谢,我很困惑。
    • 让您的 Web 服务返回一个空字符串或一个空数组,而不是 null。测试空而不是空问题已解决
    猜你喜欢
    • 2021-05-25
    • 1970-01-01
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 2021-05-14
    • 2016-10-17
    相关资源
    最近更新 更多