How to handle nested JSON in Swift 4

I'm doing my own decked out "hello world" and I've decided to handle an JSON response from an URL. I've read a lot of posts on how do handle JSON with Codable structs but I can't figure out how to create the Codable structs for this nested JSON.

{
    "acumulado": "sim",
    "cidades": [],
    "data": "2018-05-02",
    "ganhadores": [
        0,
        91,
        6675
    ],
    "numero": 2036,
    "proximo_data": "2018-05-05",
    "proximo_estimativa": 22000000,
    "rateio": [
        0,
        21948.81,
        427.46
    ],
    "sorteio": [
        7,
        8,
        19,
        23,
        27,
        58
    ],
    "valor_acumulado": 18189847.7
}

This is a sample of a JSON returned from the API, how do I create a Codable struct to handle it? Ps: I know that there are a lot of posts out there that cover this, but I can't figure out how to make it work with my sample.

Upvotes: 0

Views: 38

Answers (1)

Sulthan
Sulthan

Reputation: 130102

First of all, your JSON is not really nested:

struct MyObject: Codable {
   let acumulado: String
   let cidades: [String] // ?? hard to know what data type is there
   let numero: Int
   let proximo_data: String
   let proximo_estimativa: Int
   let rateio: [Double]
   let sorteio: [Int]
   let valor_acumulado: Double
}

Every value that can be omitted in the dictionary should be an optional (e.g. let proximo_data: String?)

You can also use CodingKeys to rename the variables:

struct MyObject: Codable {
   let acumulado: String
   let cidades: [String] // ?? hard to know what data type is there
   let numero: Int
   let proximoData: String
   let proximoEstimativa: Int
   let rateio: [Double]
   let sorteio: [Int]
   let valorAcumulado: Double

   enum CodingKeys: String, CodingKey {
     case acumulado
     case cidades
     case proximoData = "proximo_data"
     case proximoEstimativa = "proximo_estimativa"
     case rateio
     case sorteio
     case valorAcumulado
   }
}

Upvotes: 1

Related Questions