我正在尝试使用 Decodable
,但我收到一条错误消息:
KeyedDecodingContainer < CodingKeys>(_box: Swift._KeyedDecodingContainerBox< Foundation.(unknown context at 0x102f06958)._JSONKeyedDecodingContainer< MealsParser.Entry.CodingKeys>>)
我不知道为什么。
这里是 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))
}
}
如您所见,我什至无法解析包含关键餐点的容器。 稍后我希望能够解析膳食并创建内部结构等。但是,是的,我什至无法理解解析。
最佳答案
正确解码
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)
}
关于swift - 使用 SWIFT 4 decoable 时出现未知上下文错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51518022/