Shortcircuit
Shortcircuit

Reputation: 71

Swift Json Response Decoding

Trying to decode a json response from an https call. Code that is doing the decoding:

if let data = responseData, let _ = String(data: data, encoding: .utf8) {
        if let httpResponse = response as? HTTPURLResponse{
            if httpResponse.statusCode == 401 {
                print("Not Authorized")
            } else if httpResponse.statusCode == 200 {
                let decoder = JSONDecoder()
                let model: [ListResponse] = try! decoder.decode([ListResponse].self, from: data)
                print("Model: \(model)")

            }
        }
    }

It just keeps outputting an empty array. I'm obviously missing something can anyone help? I can call the method of the api from PostMan with the same information that I'm passing from Swift and it returns my values. For some reason the parsing of the return json is failing with no errors.

Edit: Response Data:

[
    {
        "id": 1,
        "numb": "12345",
        "bName": "Test Tester",
        "clDate": "2018-12-31T00:00:00",
        "currSt": "OK",
        "proPerc": 10,
        "prop": "TBD"
    },
    {
        "id": 2,
        "numb": "123456",
        "bName": "Test Tester2",
        "clDate": "2018-12-31T00:00:00",
        "currSt": "OK",
        "proPerc": 20,
        "prop": "TBD"
    }
]

Comes down to be an issue with parsing the clDate from above. Only found that error out once I converted the json to a string and tried to parse that. Trying to figure out how to handle date json parsing now.

Upvotes: 1

Views: 831

Answers (1)

Daniel T.
Daniel T.

Reputation: 33978

Put the below in a playground. The next time you have to do this sort of thing, remember Playgrounds are your friend:

struct ListResponse: Decodable {
    let id: Int
    let numb: String
    let bName: String
    let clDate: Date
    let currSt: String
    let proPerc: Int
    let prop: String
}

let myDateFormatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
    formatter.calendar = Calendar(identifier: .iso8601)
    formatter.timeZone = TimeZone(secondsFromGMT: 0)
    return formatter
}()

let text =
"""
[
{
"id": 1,
"numb": "12345",
"bName": "Test Tester",
"clDate": "2018-12-31T00:00:00",
"currSt": "OK",
"proPerc": 10,
"prop": "TBD"
},
{
"id": 2,
"numb": "123456",
"bName": "Test Tester2",
"clDate": "2018-12-31T00:00:00",
"currSt": "OK",
"proPerc": 20,
"prop": "TBD"
}
]
"""
let data = text.data(using: .utf8)!
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(myDateFormatter)
let model: [ListResponse] = try! decoder.decode([ListResponse].self, from: data)
print("Model: \(model)")

Upvotes: 1

Related Questions