【发布时间】:2020-04-02 13:53:14
【问题描述】:
{
"records": [
{
"id": 1,
"customers_name": "Acme 1"
},
{
"id": 2,
"customers_name": "Acme2"
}
]
}
这是我非常简单的 JSON 方案,但我无法让 JSONDecoder() 工作。 我的错误代码是:
本应解码 Array 但找到了字典。
这是我目前正在使用的两个文件:
客户.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 结构并尝试了很多东西,但仍然无法使其正常工作。
非常感谢你,如果有人能帮助我!
【问题讨论】:
标签: json swift jsondecoder