0

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)
AlexP
  • 449
  • 2
  • 9
  • 25

1 Answers1

2

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

vadian
  • 274,689
  • 30
  • 353
  • 361
  • 1
    Any suggestions how to make return raw Data? I tried many variations and always end up in `catch` block. – AlexP Apr 01 '18 at 11:29
  • What error do you get following the suggestion in the comments (`response.data`)? You don't even handle the actual error. – vadian Apr 01 '18 at 11:37
  • If you end up in the `catch` block there is an `error`. `print` it. `self.general_err` is pointless. Never ignore `error`s passed in a `catch` block. – vadian Apr 01 '18 at 11:44
  • `Error info: valueNotFound(Swift.Int, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "s", intValue: nil), CodingKeys(stringValue: "id", intValue: nil)], debugDescription: "Expected Int value but found null instead.", underlyingError: nil))` – AlexP Apr 01 '18 at 11:48
  • Your created structs don't match the JSON. The error message says that in the `Student` struct the value for key `id` is `nil`. The `Alamofire` part is working. – vadian Apr 01 '18 at 11:50
  • Actually it's correct since the server sends some values `nil`. in my `struct` do I need to markup it somehow to make some fields nullable? – AlexP Apr 01 '18 at 11:52
  • Just make the property optional `let id : Int?` – vadian Apr 01 '18 at 11:53
  • It Worked! Thanks A lot! Quick question if in my struct I have field that JSON doesn't contain is there a chance to avoid error? – AlexP Apr 01 '18 at 12:06
  • 1
    Use CodingKeys and leave the key out. Assign a default value to the property or make it optional. – vadian Apr 01 '18 at 12:17