{
"records": [
{
"id": 1,
"customers_name": "Acme 1"
},
{
"id": 2,
"customers_name": "Acme2"
}
]
}这是我非常简单的JSON方案,但我无法让JSONDecoder()工作。我的错误代码是:
希望解码数组,但却找到了一个字典。
以下是我目前正在使用的两个文件:
Customer.swift
struct Customer: Decodable, Identifiable {
public var id: String
public var customers_name: String
enum CodingKeys: String, CodingKey {
case id = "id"
case customers_name = "customers_name"
}
init(from decoder: Decoder) throws{
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(String.self, forKey: .id)
customers_name = (try container.decodeIfPresent(String.self, forKey: .customers_name)) ?? "Unknown customer name"
}
}CustomerFetcher.swift
import Foundation
public class CustomerFetcher: ObservableObject {
@Published var customers = [Customer]()
init(){
load()
}
func load() {
let url = URL(string: "https://somedomain.com/customers.json")!
URLSession.shared.dataTask(with: url) {(data,response,error) in
do {
if let d = data {
print(d)
let decodedLists = try JSONDecoder().decode([Customer].self, from: d)
DispatchQueue.main.async {
self.customers = decodedLists
}
} else {
print("No Data")
}
} catch {
print (error)
}
}.resume()
}
}我相信这是因为这种嵌套的JSON结构,并且尝试了这么多东西,但仍然无法使它工作。
非常感谢,如果有人愿意帮我的话!
发布于 2020-04-02 14:16:26
您正在忘记包装对象:
struct RecordList<T: Decodable>: Decodable {
let records: [T]
}
let decodedLists = try JSONDecoder().decode(RecordList<Customer>.self, from: d)
DispatchQueue.main.async {
self.customers = decodedLists.records
}还请注意,可以将Customer简化为:
struct Customer: Decodable, Identifiable {
public var id: String
public var customersName: String
enum CodingKeys: String, CodingKey {
case id
case customersName = "customers_name"
}
}您还可以设置您的JSONDecoder以自动将下划线转换为骆驼大小写。那么你甚至不需要CodingKeys了。
https://stackoverflow.com/questions/60993199
复制相似问题