Swift Json解析

起因: 之前一直用的HandyJSON,遇到了写异常的问题。在HandyJSON的GitHub发现了如下的说明

抱歉,现在已经不再建议继续使用。Swift发布4.0版本之前,官方未提供推荐的JSON处理方案,因此我们设计并实现了HandyJSON这套方案。但现在:1. Swift已经提供了Codable机制,可以相对便捷的进行JSON处理;2. HandyJSON的实现强依赖于Swift底层内存布局机制,这个机制是非公开、不被承诺、且实践证明一直在随着Swift版本变动的,HandyJSON需要跟进Swift的每次版本更新,更大的风险是,用户升级iOS版本可能会影响这个依赖,导致应用逻辑异常。综上,我们不再建议继续使用。

熟悉了下Codable,花时间把HandyJSON都换成了Codable

SwiftJSON推荐指南

遇到的问题记录

写了之后解析不出来,打印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)")
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容