gpt4 book ai didi

json - Swift 4 JSON解码

转载 作者:行者123 更新时间:2023-11-28 11:48:29 28 4
gpt4 key购买 nike

我正在尝试解码 JSON。我用于解码 JSON 的快速函数是:

func GetChapInfo(){

let endpoint = "https://chapel-logs.herokuapp.com/chapel"

let endpointUrl = URL(string: endpoint)

do {
var request = URLRequest(url: endpointUrl!)
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

let task = URLSession.shared.dataTask(with: request){
(data: Data?, response: URLResponse?, error: Error?) in


let dataAsString = String(data: data!, encoding: .utf8)
//print(dataAsString)

if(error != nil) {
print("Error")
}
else{
do{
guard let chapData = try? JSONDecoder().decode(Chapel.self, from: data!) else {
print("Error: Couldn't decode data into chapData")
return
}
for E in chapData.chap {
print(E.Day as Any)
}
}
}
}

task.resume()
}
}

我在 Swift 中的 struct

struct Chapel: Decodable {
let chap: [Chap]
}

struct Chap: Decodable {
let Name: String?
let Loc: String?
let Year: Int?
let Month: Int?
let Day: Int?
let Hour: Int?
let Min: Int?
let Sec: Int?
}

服务器的响应是:

{"chap":{"Name":"Why Chapel","Loc":"FEC","Year":2018,"Month":9,"Day":4,"Hour":16,"Min":1,"Sec":7}}

但是,当我运行这个程序时,程序打印出“错误:无法将数据解码为 chapData”,我无法弄清楚原因。

最佳答案

首先 catch 解码错误。从不try? .捕获的错误更具描述性

Expected to decode Array<Any> but found a dictionary instead

表示:key chap 的值是字典,不是数组

struct Chapel: Decodable {
let chap: Chap
}

然后你必须打印

print(chapData.chap.Day) 

您可以减少代码。明确的 URLRequest不需要默认 GET 请求的 header 。这足够了:

let endpoint = "https://chapel-logs.herokuapp.com/chapel"
let endpointUrl = URL(string: endpoint)!

do {

let task = URLSession.shared.dataTask(with: endpointUrl) { (data, response, error) in
...

关于json - Swift 4 JSON解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52171020/

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