Alan Lau
Alan Lau

Reputation: 125

How to get JSON array value in Swift using Codable

I'm having trouble getting the direction values from the following JSON:

"routeOptions": [
        {
          "name": "Jubilee",
          "directions": [
            "Wembley Park Underground Station",
            "Stanmore Underground Station"
          ],
          "lineIdentifier": {
            "id": "jubilee",
            "name": "Jubilee",
            "uri": "/Line/jubilee",
            "type": "Line",
            "routeType": "Unknown",
            "status": "Unknown"
          }
        }
      ]

I believe the directions is a JSON array, which at the moment I'm using Codable as below. I've managed to get the routeOptions name but can't seem to figure out how to get the directions as there's no specific key variable. Please can someone help?

struct RouteOptions: Codable {

let name: String?
let directions: [Directions]?

init(name: String, directions: [Directions]) {
    self.name = name
    self.directions = directions
}}

struct Directions: Codable {}

Upvotes: 0

Views: 81

Answers (1)

Joakim Danielson
Joakim Danielson

Reputation: 51861

You need to handle directions as an array of String

struct RouteOptions: Codable {
    let name: String
    let directions: [String]
}

Here is an example where I fixed the json to be correct

let data = """
{ "routeOptions": [
  {
    "name": "Jubilee",
    "directions": [
      "Wembley Park Underground Station",
      "Stanmore Underground Station"
    ],
    "lineIdentifier": {
      "id": "jubilee",
      "name": "Jubilee",
      "uri": "/Line/jubilee",
      "type": "Line",
      "routeType": "Unknown",
      "status": "Unknown"
    }
  }
]}
""".data(using: .utf8)!

struct Root: Decodable {
    let routeOptions: [RouteOptions]
}

struct RouteOptions: Codable {
    let name: String
    let directions: [String]
}

do {
    let result = try JSONDecoder().decode(Root.self, from: data)
    print(result.routeOptions)
} catch {
    print(error)
}

Upvotes: 1

Related Questions