swift 4 decoder STRUCT MAPPING JSON

0

I have this json structure and what I want to do for now is just print it on the console, I'm learning to map a json

my struct:

struct Buscajson: Decodable {

        let status: Int?
        let mensaje:String?
        let empresas: empresa?
    }

    struct empresa: Decodable {

        let id :Int?
        let nombre :String?
        let sitioweb :String?
        let logo : String?
        let fechaFundacion :String?
        let fundadores :[fundador]?
        let productos :[producto]?


    }     struct fundador:Decodable {

        let nombre:String
        let foto:String
    }

    struct producto: Decodable {

        let nombre:String
        let icono:String

    }

and here is my code:

    let JSONurlString = "http://payrapid.net/API/LoginBecariosPost.php?user=Apple&password=@PPL3?"

    guard let url = URL(string: JSONurlString) else { return }

    URLSession.shared.dataTask(with: url) { (data, response, err) in



        guard let data = data else { return }

        do {

            let buscado = try JSONDecoder().decode(Buscajson.self, from: data)
            print(buscado)




        } catch let jsonError {

        print("error en la serializacion de json",jsonError)
        }




        }.resume()
}

but when I try to print in the company console I get null, my question is how do I represent the company in the structure to read the other fields?:

Buscajson # 1 (status: Optional (1), message: Optional ("Login successfully"), companies: nil)

How can I print what else they contain with structures, or can not, would it only be with for cycles and NSDictionary and NSArray, NSObject and all that?

    
asked by Carlos Méndez 24.08.2017 в 00:57
source

1 answer

0

In the json that you receive as an answer, the key of the object is company and not companies (note the "s" of the plural) so the parsing fails.

You have two options:

  • Change the definition of the struct Buscajson to:

    struct Buscajson : Codable {
        let status   : Int?
        let mensaje  : String?
        let empresa  : Empresa?
    }
    
  • To specify the keys, you can add a enum CodingKeys: String, CodingKey :

    struct Buscajson : Decodable {
    
        let status   : Int?
        let mensaje  : String?
        let empresas : Empresa?
    
        enum CodingKeys: String, CodingKey {
            case status
            case mensaje
            case empresas = "empresa"
        }
    }
    
  • answered by 25.08.2017 в 18:58