gpt4 book ai didi

json - 解析 Json 显示错误 keyNotFound Swift

转载 作者:行者123 更新时间:2023-11-30 10:31:26 25 4
gpt4 key购买 nike

我想解析 json,但 Xcode 显示此消息:keyNotFound(CodingKeys(stringValue: "Id", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "没有关联的值带有键 CodingKeys(stringValue:\"Id\", intValue: nil) (\"Id\").",underlyingError: nil))

JSON:

{
"result": [
{
"Id": 5,
"Title": "Test1",
"EnTitle": "Story and Novel"
},
{
"Id": 38,
"Title": "Test2",
"EnTitle": " Motivational"
}

],
"status": {
"message": "Confirm",
"success": true,
"systemDateTime": "2019-11-01T12:07:05+03:30",
"httpStatusCode": 200
}
}

型号:

struct Result : Decodable {
let Id : Int
let Title : String
let EnTitle : String
}

class ResultInitialiser {

let Id : Int
let Title : String
let EnTitle : String

init(Id:Int, Title:String, EnTitle: String) {
self.Id = Id
self.Title = Title
self.EnTitle = EnTitle
}

}

View Controller :

var genresFetch = [Result]()
var structGenresFetch = [ResultInitialiser]()
let headers : HTTPHeaders = ["Token" : "6f8652e3-d9d9-4b34-9455-0fa32e82ec58"]

AF.request(BASE_URL!, method: .get, headers: headers).response { (response) in
do {
self.genresFetch = [try JSONDecoder().decode(Result.self, from: response.data!)]

for eachProduct in self.genresFetch {

let recived_Data = ResultInitialiser(Id: eachProduct.Id, Title: eachProduct.Title, EnTitle: eachProduct.EnTitle)
self.structGenresFetch.append(recived_Data)
print(eachProduct.Title)
DispatchQueue.main.async {
self.tvMainApi.reloadData()
}
}
}catch {
print(error)
}
}

最佳答案

JSONDecoder 将尝试从根开始解码 JSON。在根级别,只有两个键,resultsstatus。您传递给它的 Decodable 类型 Result 没有这些键。

您需要创建另一个结构:

struct Response {
let results: [Result]
}

并解码此结构:

    do {
// notice the change to this line
self.genresFetch = try JSONDecoder().decode(Response.self, from: response.data!).results
...
}catch {
print(error)
}

IMO,您不需要名为 ResultInitialiser 的额外 class。仅使用结构体作为模型有什么问题?

关于json - 解析 Json 显示错误 keyNotFound Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59124107/

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