gpt4 book ai didi

ios - JSON 解码器因 URLSession 失败

转载 作者:行者123 更新时间:2023-12-01 19:31:53 34 4
gpt4 key购买 nike

Swift 的新手,本周尝试学习 SwiftUI。尝试从 Joke API 发出 GET 请求,并最终希望每次按下按钮时都刷新它。

我有一种感觉,我错误地定义了我的结构,或者可能没有正确解码返回的数据。我可以打印数据字符串(作为 json 字典),但不能通过 Swift 访问值本身。

import SwiftUI

struct Response : Codable {
var joke: [Joke]
}

struct Joke : Codable {
var setup: String
var delivery: String
}

struct ContentView : View {
@State private var joke = [Joke]()

func loadData() {
guard let url = URL(string: "https://sv443.net/jokeapi/v2/joke/Dark?type=twopart") else {
print("Invalid URL")
return
}

URLSession.shared.dataTask(with: url) { data, res, error in
if let data = data {
print("decoding...")
let str = String(data: data, encoding: .utf8)
print(str!)

if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
print("decoded!")
// cannot get this to print
print(decodedResponse.joke)

// looks good, let's get out of here
return
}
}
print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
}.resume()
}

var body : some View {
Text("test")
.onAppear(perform: loadData)
}
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

decoding...
{
"category": "Dark",
"type": "twopart",
"setup": "When I was a kid, I made a really big sandcastle with my grandma.",
"delivery": "Unfortunately that didn't impress anyone at the cremation...",
"flags": {
"nsfw": false,
"religious": false,
"political": false,
"racist": false,
"sexist": false
},
"id": 145,
"error": false
}
Fetch failed: Unknown error

可能只是我没有发现的愚蠢错误,但希望得到一些解释甚至一些文档。我见过的唯一文档/教程展示了如何使用特定结构化的 JSON 响应。我拉的那个根有一本字典,所以我想这就是差异所在。

我假设我会使用 @escaping 在 UI 中进行渲染?

最佳答案

问题是您正在尝试解码数组:

struct Response : Codable {
var joke: [Joke]
}

struct Joke : Codable {
var setup: String
var delivery: String
}

然而,JSON 响应只是一个对象。

解决方案可能是将其解码为对象而不是数组:
struct Response : Codable {
var setup: String
var delivery: String
}

或者,将解码部分更改为解码 Joke :
let decodedResponse = try? JSONDecoder().decode(Joke.self, from: data)

关于ios - JSON 解码器因 URLSession 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62334464/

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