Krunal Nagvadia
Krunal Nagvadia

Reputation: 1162

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

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

Upvotes: 2

Views: 12142

Answers (2)

staticVoidMan
staticVoidMan

Reputation: 20234

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

Upvotes: 3

Yash Jadhav
Yash Jadhav

Reputation: 321

I would like to recommend you to use json4swift.com. You just have to copy your json and paste there. It will automatically create modal struct or class from your json.

Coming back to your question, Your class Album doesn't have array of [_source]. That's the reason you are getting following error "The data couldn’t be read because it isn’t in the correct format".

Try below given format of album class,

class Album: Codable
{ 
  var source: Source?
  var id: String?
}

Please try to avoid using underscore in Swift.

Upvotes: 1

Related Questions