0

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 {}
2
  • 1
    That's invalid JSON - it should always start with a dictionary or array, and as such Codable won't handle it. Remove the "routeOptions": to make it valid. Commented Jan 28, 2020 at 21:19
  • jsonformatter.org/json-parser is a great tool for checking your JSON, Commented Jan 28, 2020 at 21:19

1 Answer 1

1

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)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.