0

I'm trying to initialize a struct so I can parse from a JSON file in Swift. I have the following written:

struct StopDescription: Decodable {
    let stopId: String
    let translocStopId: String
    let stopName: String
    let stopDesc: String
    let stopLat: String
    let stopLon: String
    let directionId: String
    let times: [String]
}

In order to parse from this JSON code:

{
    stop_id: "M1",
    transloc_stop_id: "4160714",
    stop_name: "blank",
    stop_desc: "blank",
    stop_lat: "142",
    stop_lon: "-171",
    direction_id: "1",
    times: [
        "7:00 AM",
        "7:30 AM",
        "8:00 AM",
        "8:30 AM",
        "8:45 AM",
        "9:00 AM",
        "9:30 AM",
        "10:00 AM",
        "10:30 AM",
        "11:00 AM",
        "11:30 AM"
    ]
}

I'm not entirely sure if my Array declaration for the times variable is correct. Could someone please point me in the right direction?

3
  • It's a lot easier if you paste the code as formatted text into your question. Following the links for images isn't helpful. Commented May 24, 2018 at 15:14
  • I apologize. I have edited the comment accordingly. Commented May 24, 2018 at 15:19
  • 1
    Technically, your JSON is not JSON. You have to double quote the keys as well as the string values. If your JSON parser is bailing, that's probably the problem. Commented May 24, 2018 at 15:22

1 Answer 1

1

Yes, it is correct. Be sure to either add a CodingKeys enum or more preferably use the .convertFromSnakeCase as the keyDecodingStrategy when you parse the JSON.

struct StopDescription: Codable {
    let stopId, translocStopId, stopName, stopDesc: String
    let stopLat, stopLon, directionId: String
    let times: [String]
}

let let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase

let stopDescription = try? decoder.decode(StopDescription.self, from: jsonData)
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.