Search code examples
jsonswiftserializationjsondecoder

Error Serialization


Why do I can't access all the properties inside of "data" struct by doing this way? Otherwise, I don't know how to parse all the data inside of "Data" array.

This is how I'm trying to serialize:

import Foundation
import Alamofire

struct Description: Decodable {
    let _data: [data]
}
struct data: Decodable {
    let id:Int?
    let descricao:String?
    let urlImagem:String?
}
func callApi() {

    guard let _url = URL(string: "https://alodjinha.herokuapp.com/categoria")else{return}
    Alamofire.request(_url).responseJSON { (response) in

        guard let _data = response.data else{return}
        //let dataString = String(data: _data, encoding: .utf8)

        do{
            let dataParsed = try JSONDecoder().decode([Description].self, from: _data)
                print(dataParsed.id)


        }catch{
            print("Error serialization")}



}
}

I'm getting the error:

Error serialization: typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))

The JSON model that I'm following:

 {
    "data":[
        {
            "id":1,
            "descricao":"Games",
            "urlImagem":"http://39ahd9aq5l9101brf3b8dq58.wpengine.netdna-cdn.com/wp-content/uploads/2013/06/3D-Gaming.png"
        },
        {
            "id":2,
            "descricao":"Livros",
            "urlImagem":"http://4.bp.blogspot.com/-6Bta1H9d22g/UJAIJbqcHhI/AAAAAAAAKi4/hvgjWrlFc64/s1600/resenha-missiologia.png"
        },
        {
            "id":3,
            "descricao":"Celulares",
            "urlImagem":"http://pt.seaicons.com/wp-content/uploads/2015/11/Mobile-Smartphone-icon.png"
        },
        {
            "id":4,
            "descricao":"Informática",
            "urlImagem":"http://portal.ifrn.edu.br/campus/ceara-mirim/noticias/ifrn-oferece-curso-de-informatica-basica-para-pais-dos-estudantes/image_preview"
        },
        {
            "id":5,
            "descricao":"Eletrodoméstico",
            "urlImagem":"http://classificados.folharegiao.com.br/files/classificados_categoria/photo/8/sm_4d5ed3beb0f31b61cb9a01e46ecd0cf9.png"
        },
        {
            "id":6,
            "descricao":"TVs",
            "urlImagem":"http://i.utdstc.com/icons/256/terrarium-tv-android.png"
        },
        {
            "id":7,
            "descricao":"Filmes e Séries",
            "urlImagem":"https://pbs.twimg.com/profile_images/801033586438733824/91Y_N91t_reasonably_small.jpg"
        },
        {
            "id":8,
            "descricao":"Móveis e Decorações",
            "urlImagem":"https://image.flaticon.com/icons/png/128/148/148188.png"
        },
        {
            "id":9,
            "descricao":"Moda, Beleza e Perfumaria",
            "urlImagem":"http://icon-icons.com/icons2/196/PNG/128/fashion_23852.png"
        },
        {
            "id":10,
            "descricao":"Papelaria",
            "urlImagem":"http://esen.pt/in/images/stories/skills_256.png"
        }
    ]
}

Solution

  • First, the error indicates that you only have one Description in the JSON but your code is attempting to get an array.

    You need to change:

    let dataParsed = try JSONDecoder().decode([Description].self, from: _data)
    

    to:

    let dataParsed = try JSONDecoder().decode(Description.self, from: _data)
    

    Now you need to iterate the array of data.

    This means you need code similar to:

    for aData in dataParsed._data {
        print(aData.id)
    }
    

    FYI - class, struct, and enum names should start with uppercase letters. Functions, variables, and case names should start with lowercase letters.

    Also avoid using _ in variable names.