所以基本上,我试图读取有关一些支出的本地json文件。我有一个结构“支出”和一个结构“支出”,其中包含一系列支出。使用Spendings类型进行解码时,无法访问json中的数据。
我尝试使用正在运行的[Spending.self]进行解码,但是我想使用结构Spendings,但我不知道为什么它不起作用?
[
{
"id": 1,
"name": "Métro 052",
"price": 8.97,
"date": "22/07/2019",
"category": "Transport"
},
{
"id": 2,
"name": "National Geographic Museum",
"price": 10.77,
"date": "22/07/2019",
"category": "Museum"
}
]
enum Categories: String, Codable {
case Transport
case Food
case Museum
case Mobile
case Housing
case Gifts
case Shopping
}
struct Spending: Codable {
var id: Int
var name: String
var price: Float
var date: String
var category: Categories
}
struct Spendings: Codable {
let list: [Spending]
}
//Not working
class SpendingController {
static let shared = SpendingController()
func fetchSpendings(completion: @escaping ([Spending]?) -> Void) {
if let filepath = Bundle.main.path(forResource: "spending", ofType: "json") {
let jsonDecoder = JSONDecoder()
if let data = try? Data(contentsOf: URL(fileURLWithPath: filepath)), let spendings = try? jsonDecoder.decode(Spendings.self, from: data) {
completion(spendings.list)
}
}
}
}
//Working
class SpendingController {
static let shared = SpendingController()
func fetchSpendings(completion: @escaping ([Spending]?) -> Void) {
if let filepath = Bundle.main.path(forResource: "spending", ofType: "json") {
let jsonDecoder = JSONDecoder()
if let data = try? Data(contentsOf: URL(fileURLWithPath: filepath)), let spendings = try? jsonDecoder.decode([Spending].self, from: data) {
completion(spendings)
}
}
}
}
我没有任何错误消息,但是在完成打印结果时,与使用[Spending] .self时相反,没有打印任何内容。
答案 0 :(得分:4)
在这里解码[Spending].self
确实是正确的,因为JSON的根是一个数组,这意味着您用来解码的类型应该是[XXX].self
。
在此处解码Spendings.self
是不正确的,因为这意味着您正在解码的是对象根,而不是数组的根。 Spendings
结构具有单个属性list
,因此JSON的根对象需要具有密钥"list"
才能解码Spendings.self
才能正常工作,如下所示:
{
"list":
[
{
"id": 1,
"name": "Métro 052",
"price": 8.97,
"date": "22/07/2019",
"category": "Transport"
},
{
"id": 2,
"name": "National Geographic Museum",
"price": 10.77,
"date": "22/07/2019",
"category": "Museum"
}
]
}