Swift : The data couldn’t be read because it isn’t in the correct format

Krunal Nagvadia picture Krunal Nagvadia · Mar 6, 2019 · Viewed 8.9k times · Source

I try to call the POST Api with Alamofire but it's showing me an error of incorrect format.

This is my JSON response:

[
  {
    "_source": {
      "nome": "LOTERIAS BELEM",
      "endereco": "R DO COMERCIO, 279",
      "uf": "AL",
      "cidade": "BELEM",
      "bairro": "CENTRO"
    },
    "_id": "010177175"
  },
  {
    "_source": {
      "nome": "Bel Loterias"
    },
    "_id": "80224903"
  },
  {
    "_source": {
      "nome": "BELLEZA LOTERIAS",
      "endereco": "R RIVADAVIA CORREA, 498",
      "uf": "RS",
      "cidade": "SANTANA DO LIVRAMENTO",
      "bairro": "CENTRO"
    },
    "_id": "180124986"
  }
]

class Album: Codable {
    var _source :  [_source]

}

class _source: Codable {
    var nome :  String
    var endereco : String
    var uf : String
    var cidade : String
    var bairro : String
}

var arrList = [Album]()

And this is how i try to Decoding with Alamofire.

func request() {

        let urlString = URL(string: "My Url")
      //  Alamofire.request(url!).responseJSON {(response) in

        Alamofire.request(urlString!, method: .post, parameters: ["name": "belem"],encoding: JSONEncoding.default, headers: nil).responseJSON {
            (response) in

            switch (response.result) {
            case .success:
                if let data = response.data {
                    do {
                        let response = try JSONDecoder().decode([Album].self, from: data)
                        DispatchQueue.main.async {
                             self.arrList = response
                        }
                    }
                    catch {
                        print(error.localizedDescription)
                    }
                }
            case .failure( let error):
                print(error)
            }
       }
 }

Answer

staticVoidMan picture staticVoidMan · Mar 7, 2019

Just your Album model is incorrect.

struct Album: Codable {
    var source : Source
    var id     : String

    enum CodingKeys: String, CodingKey {
        case source = "_source"
        case id = "_id"
    }
}

struct Source: Codable {
    var nome     : String
    var endereco : String?
    var uf       : String?
    var cidade   : String?
    var bairro   : String?
}

If you don't want _id altogether then simply remove the related parts.
As for your Alamofire related code, that part is good.


Notable improvements:

  • Have avoided underscored variable name in model by customizing CodingKeys for key mapping purpose
  • Typenames should always start with a Capital letter (so _source is Source)
    • Similarly, variable names should always start with a lowercase letter
  • Made some variables optional (based on your updated response)
    • Keeping a variable non-optional means it must be present in the response for the model to be created
    • Making a variable optional means that key may or may not be present in the response and it not being there won't prevent the model from being created