Search code examples
swiftalamofireswift4jsondecoder

SWift 4 JSONDecoder decode from Alamofire response


I have a structure that contains another structures and arrays.

public struct Report: Codable {
 let s:Student;
 let vio:[VIO];
 let  stuPresence: [StuPresence]; 
}

I am trying new JSONDecoder() to transform alamofire response into my struct.

sessionManager.request( self.url_report+"?d="+date, method: .get, parameters: nil).responseJSON{ response in
    if response.response?.statusCode == 200 {
            debugPrint(response)
            do{
                let r = try JSONDecoder().decode(Report.self, from: response.result.value as! Data)
                debugPrint(r);
            }catch{
               self.showMessage(message: self.general_err)
            }
    }
}

The problem is that instead of strings after decoding in my Report struct I get numbers (checked from debugging mode). What am I doing wrong?

UPDATE: it also gives error

Could not cast value of type '__NSDictionaryI' (0x108011508) to 'NSData' (0x108010090)

Solution

  • The error is pretty clear:

    response.result.value is obviously a dictionary (__NSDictionaryI) which cannot be casted to (NS)Data. That means that the JSON is already deserialized.

    To be able to use JSONDecoder you have to change your Alamofire settings to return raw Data