Swift Json响应解码

时间:2018-12-31 21:58:30

标签: ios swift swift4

尝试解码来自https调用的json响应。 正在执行解码的代码:

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)")

            }
        }
    }

它只是一直输出一个空数组。我显然缺少任何人都可以帮忙的东西?我可以使用与我从Swift传递过来的信息相同的信息,从PostMan调用api的方法,它返回我的值。由于某种原因,返回json的解析失败,没有错误。

编辑: 响应数据:

[
    {
        "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"
    }
]

从上面解析clDate成为一个问题。只有在将json转换为字符串并尝试解析该错误后,才发现该错误。试图弄清楚如何立即处理日期json解析。

1 个答案:

答案 0 :(得分:1)

将以下物品放在操场上。下次您必须执行此类操作时,请记住Playgrounds是您的朋友:

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)")