7

I am using AlamofireObjectMapper, whenever the response contains any null value, it gives an error,

"FAILURE: Error Domain=com.alamofireobjectmapper.error Code=2 "ObjectMapper failed to serialize response." UserInfo={NSLocalizedFailureReason=ObjectMapper failed to serialize response.}"

This is how I am requesting

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)           
                }
            }
        }

And this is my DataModel 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"]
    }
}

I also tried adding blank parameters as this api requires no parameters and also added default URl encoding but no help.

I don't know where I am missing something, this code works fine when there is not any null in the api response. Please help!!

Thanks

Aakash
  • 2,239
  • 15
  • 23

1 Answers1

2

Your code has no problem, but the JSON in the URL is malformed. The temperature field of the third object is empty.

  • This is my question, why it does not serialize the response when there is null value in the response as there might be a case when I may get a null response and at that time my code should replace that null with an empty value. – Aakash Sep 20 '16 at 05:16
  • I just want to know if there is any way I can make it replace null values with respective default values. – Aakash Sep 20 '16 at 05:18
  • I understand you, but the json is malformed and not null value in the temperature field of the third element of the array. – danbarbozza Sep 20 '16 at 12:43
  • Thanks, I was confused. – Aakash Sep 21 '16 at 09:04
  • Have your web service return an empty string or an empty array instead of null. Test for empty rather than null problem solved – jcpennypincher Mar 21 '18 at 22:03