SwiftUI - 发出获取请求时收到错误
SwiftUI - Error Received When Making Get Request
我在执行 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))
这是我正在使用的发出获取请求的代码:
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 对象中返回的缺失部分添加到我的数据模型中。见下文:
struct Get: Codable, Identifiable {
var userId: Int //newly added
var id: Int //newly added
var title: String
var body: String
我在执行 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))
这是我正在使用的发出获取请求的代码:
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 对象中返回的缺失部分添加到我的数据模型中。见下文:
struct Get: Codable, Identifiable {
var userId: Int //newly added
var id: Int //newly added
var title: String
var body: String