Swift 4 decoding json using Codable

Check the outlined structure of your JSON text:

{
    "success": true,
    "message": "got the locations!",
    "data": {
      ...
    }
}

The value for "data" is a JSON object {...}, it is not an array. And the structure of the object:

{
    "LocationList": [
      ...
    ]
}

The object has a single entry "LocationList": [...] and its value is an array [...].

You may need one more struct:

struct Location: Codable {
    var data: LocationData
}

struct LocationData: Codable {
    var LocationList: [LocationItem]
}

struct LocationItem: Codable {
    var LocID: Int!
    var LocName: String!
}

For testing...

var jsonText = """
{
    "success": true,
    "message": "got the locations!",
    "data": {
        "LocationList": [
            {
                "LocID": 1,
                "LocName": "Downtown"
            },
            {
                "LocID": 2,
                "LocName": "Uptown"
            },
            {
                "LocID": 3,
                "LocName": "Midtown"
            }
        ]
    }
}
"""

let data = jsonText.data(using: .utf8)!
do {
    let locList = try JSONDecoder().decode(Location.self, from: data)
    print(locList)
} catch let error {
    print(error)
}

Tags:

Swift4

Codable