我正在尝试玩Decodable
,但出现错误:
KeyedDecodingContainer
(_ box:Swift._KeyedDecodingContainerBox >)
我不知道为什么。
这是JSON:
{
"meals": {
"breakfast": {
"cost": 24,
"min_price": 4
},
"lunch": {
"cost": 12,
"min_price": 2,
"max_price": 20
},
"dinner": {
"cost": 42
}
}
}
代码如下:
import UIKit
struct Meal: Decodable {
var price: Int?
}
struct Entry: Decodable {
enum CodingKeys: String, CodingKey {
case meals
}
var meals: String?
// var meals: [String: Meal]
public init(from decoder: Decoder) throws {
var values = try decoder.container(keyedBy: CodingKeys.self)
print(values)
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let url = Bundle.main.url(forResource: "meal", withExtension: "json")
let data = try! Data(contentsOf: url!)
let decoder = JSONDecoder()
print(try! decoder.decode(Entry.self, from: data))
}
}
如您所见,我什至无法解析关键食物的容器。 后来我希望能够解析进餐并创建内部结构等。但是,是的,我什至不会进行解析。
答案 0 :(得分:2)
正确解码
struct Root: Codable {
let meals: Meals
}
struct Meals: Codable {
let breakfast: Breakfast
let lunch: Lunch
let dinner: Dinner
}
struct Breakfast: Codable {
let cost, minPrice: Int
enum CodingKeys: String, CodingKey {
case cost
case minPrice = "min_price"
}
}
struct Dinner: Codable {
let cost: Int
}
struct Lunch: Codable {
let cost, minPrice, maxPrice: Int
enum CodingKeys: String, CodingKey {
case cost
case minPrice = "min_price"
case maxPrice = "max_price"
}
}
//
do {
let content = try JSONDecoder().decode(Root.self, from: data)
print(content)
}
catch {
print(error)
}