起因: 之前一直用的HandyJSON,遇到了寫異常的問題。在HandyJSON的GitHub發(fā)現(xiàn)了如下的說明
熟悉了下Codable,花時間把HandyJSON都換成了Codable
遇到的問題記錄
寫了之后解析不出來,打印error.description 也得不到有用信息
解決方案: 直接打印error 會有一串描述信息,仔細(xì)找哪些鍵值出了問題
可能的問題 值的類型不對 鍵沒有對應(yīng)的值
改變鍵值的映射
let json = """
[
{
"product_name": "Bananas",
"product_cost": 200,
"description": "A banana grown in Ecuador."
},
{
"product_name": "Oranges",
"product_cost": 100,
"description": "A juicy orange."
}
]
""".data(using: .utf8)!
struct GroceryProduct: Codable {
var name: String
var points: Int
var description: String?
private enum CodingKeys: String, CodingKey {
case name = "product_name"
case points = "product_cost"
case description
}
}
let decoder = JSONDecoder()
let products = try decoder.decode([GroceryProduct].self, from: json)
print("The following products are available:")
for product in products {
print("\t\(product.name) (\(product.points) points)")
if let description = product.description {
print("\t\t\(description)")
}
}