Search code examples
arraysjsonswiftalamofire

Swift 4 json array - how to get value


I have this code in Swift 4 and Alamofire:

Alamofire.request("http://xxxx.pl/id=1", method: .get, parameters: nil)
            .responseJSON { response in
let jsonResponse = JSON(response.result.value!)

let resData = jsonResponse["ranking"].array
print("XXXX: \(jsonResponse)")
}
            .responseString { response in
                if let error = response.result.error {
                    print(error)
                }
                if let value = response.result.value {
                    print(value)
                }
}

After running this code, I get a json with the following parameters:

XXXX: {
  "ranking" : {
    "dataWidoczneOd" : {
      "second" : 0,
      "year" : 2018,
      "month" : 2,
      "hourOfDay" : 0,
      "dayOfMonth" : 1,
      "minute" : 0
    }
    "opis" : "cx",
    "id" : 50971,
    "dataWidoczneDo" : {
      "second" : 0,
      "year" : 2018,
      "month" : 2,
      "hourOfDay" : 0,
      "dayOfMonth" : 31,
      "minute" : 0
    },
    "grupy" : [
      {
        "nazwa" : "yyy",
        "kod" : "yyy",
        "id" : 51032,
        "idkiPlikowGrafiki" : [
          "51034"
        ],
        "gracze" : [

          {
            "zakonczonaGra" : false,
            "imieINazwisko" : "zzzz yyyy",
            "email" : "[email protected]",
            "liczbaZdobytychPunktow" : "0.0",
            "czasGry" : "0 min"
          }
        ]
      },
      {
        "nazwa" : "ttt",
        "kod" : "ttt",
        "id" : 50981,
        "idkiPlikowGrafiki" : [
          "50983",
          "50986"
        ],
        "gracze" : [

        ]
      }
    ],
    "nazwa" : "grupowy",
    "idkiPlikowGrafiki" : [
      "50976"
    ],
    "typ" : "GRUPA",
    "dataOd" : {
      "second" : 0,
      "year" : 2018,
      "month" : 2,
      "hourOfDay" : 0,
      "dayOfMonth" : 1,
      "minute" : 0
    }
  }
}

How can I get the values from this json array and save in variables: - gracze (all values) - idkiPlikowGrafiki (all values) - typ (all values) - kod (all values) - dataWidoczneOd (all values)

?

Please help :)


Solution

  • You should create a model class for this response and parse it with, for example, Codable. Here is a good example.