小编Khr*_*riy的帖子

如果单个元素解码失败,Swift JSONDecode解码数组将失败

在使用Swift4和Codable协议时,我遇到了以下问题 - 看起来没有办法允许JSONDecoder跳过数组中的元素.例如,我有以下JSON:

[
    {
        "name": "Banana",
        "points": 200,
        "description": "A banana grown in Ecuador."
    },
    {
        "name": "Orange"
    }
]
Run Code Online (Sandbox Code Playgroud)

还有一个Codable结构:

struct GroceryProduct: Codable {
    var name: String
    var points: Int
    var description: String?
}
Run Code Online (Sandbox Code Playgroud)

解码这个json时

let decoder = JSONDecoder()
let products = try decoder.decode([GroceryProduct].self, from: json)
Run Code Online (Sandbox Code Playgroud)

结果products是空的.这是可以预料到的,因为JSON中的第二个对象没有"points"键,而struct中points不是可选的GroceryProduct.

问题是如何允许JSONDecoder"跳过"无效对象?

arrays json swift swift4 codable

86
推荐指数
8
解决办法
4万
查看次数

标签 统计

arrays ×1

codable ×1

json ×1

swift ×1

swift4 ×1