gpt4 book ai didi

ios - Swift Json 响应解码

转载 作者:行者123 更新时间:2023-11-28 05:47:54 24 4
gpt4 key购买 nike

尝试解码来自 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 解析。

最佳答案

将下面的内容放在 Playground 上。下次你不得不做这种事情时,请记住 Playgrounds 是你的 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)")

关于ios - Swift Json 响应解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53991722/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com