首页 > 解决方案 > 带有 Codable 的可失败初始化器

问题描述

我正在尝试解析项目数组的以下 json 模式,itemID 可能不为空。如何使itemIDJSON 中不存在项目 nil id?

[{
    "itemID": "123",
    "itemTitle": "Hello"
  },
  {},
  ...
]

我的可解码类如下:

public struct Item: : NSObject, Codable {
    let itemID: String
    let itemTitle: String?
}

private enum CodingKeys: String, CodingKey {
    case itemID
    case itemTitle
}

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)

        itemID = try container.decode(String.self, forKey: .itemID)
        itemTitle = try container.decodeIfPresent(String.self, forKey: .itemTitle)

        super.init()
    }
}

标签: swiftcodable

解决方案


首先,itemIDis an Intand not Stringin your JSONresponse。所以struct Item看起来,

public struct Item: Codable {
    let itemID: Int?
    let itemTitle: String?
}

解析之JSON类的,

if let data = data {
    do {
        let items = try JSONDecoder().decode([Item].self, from: data).filter({$0.itemID == nil})
        print(items)
    } catch {
        print(error)
    }
}

在上面的代码中,您可以简单地filter使用itemID == nil.


推荐阅读