1

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.

9
  • where does the data come from? Your code looks good. If the model is an empty array, you should look into your backend service. Commented Dec 31, 2018 at 22:04
  • Sorry I add an edit that may explain that. It comes from an API. I can call the same method from postman and it returns values with the same parameters being passed. Commented Dec 31, 2018 at 22:05
  • Please post some sample data that you get using postman Commented Dec 31, 2018 at 22:09
  • let json = try JSON(data: data); print(json); Can you print the data? You can check the data if it is empty. Commented Dec 31, 2018 at 22:19
  • So, not entirely sure if this is the same as what you asked. What you asked for was throwing me compiler errors so, I did this: let JSON = try! JSONSerialization.jsonObject(with: data, options: []) print("Json: (JSON)") returns a blank output Commented Dec 31, 2018 at 22:44

1 Answer 1

1

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

2 Comments

does the clDate have to be a string for this to work? Technically it is a DateTime data type from the api.
I updated to account for the Date. Not only is playground your friend, so is Google: useyourloaf.com/blog/swift-codable-with-custom-dates

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.