【发布时间】:2021-07-15 23:07:29
【问题描述】:
我在执行 JSON 获取请求时收到以下错误:
Thread 6: Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "id", intValue: nil)], debugDescription: "Expected to decode String but found a number instead.", underlyingError: nil))
这是我正在使用的发出 fetch 请求的代码:
struct Get: Codable, Identifiable {
var id = UUID()
var title: String
var body: String
//var meals: [[String: String?]]
//var strInstructions: String
}
class Api {
func getData(completion: @escaping ([Get]) -> ()) {
guard let url = URL(string: "https://jsonplaceholder.typicode.com/posts") else {return}
URLSession.shared.dataTask(with: url) { (data, _, _) in
let get = try! JSONDecoder().decode([Get].self, from: data!) //The error appears on this line - the ".decode" gets underlined as the source of the error
DispatchQueue.main.async {
completion(get)
}
}
.resume()
}
最后,这是我设置的演示视图,用于显示数据:
struct apitestview: View {
@State var getRecipe: [Get] = []
var body: some View {
List(getRecipe) { get in
Text(get.body)
}
.onAppear() {
Api().getData { (get) in
self.getRecipe = get
}
}
}
有什么想法吗?我已经尝试了上面代码的几种不同变体,但我似乎无法找到错误的根源。
编辑:
这是一段 JSON 数据
[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
}
]
【问题讨论】:
-
显示您的数据样本。为什么要强制解包“数据”?为什么要强制展开尝试?
-
我在帖子中添加了一段 JSON。
-
比较 Get 结构和示例数据集,您应该注意到自己的错误。
-
啊哈!我将缺失的部分添加到我的数据模型(userId 和 Id)中并且它起作用了。感谢您为我指明正确的方向!