起因: 之前一直用的HandyJSON,遇到了写异常的问题。在HandyJSON的GitHub发现了如下的说明
熟悉了下Codable,花时间把HandyJSON都换成了Codable
遇到的问题记录
写了之后解析不出来,打印error.description 也得不到有用信息
解决方案: 直接打印error 会有一串描述信息,仔细找哪些键值出了问题
可能的问题 值的类型不对 键没有对应的值
改变键值的映射
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)")
}
}
网友评论