带有编码器的初始化失败 [英] Failable Initializers with Codable

查看:321
本文介绍了带有编码器的初始化失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm attempting to parse the following json schema of array of items, itemID may not be empty. How do I make an item nil id itemID does not exist in the JSON?

[{
    "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()
    }
}


推荐答案

首先, itemID JSON 响应中的 Int 而不是 String 。因此结构项看起来像

First of all, itemID is an Int and not String in your JSON response. So the struct Item looks like,

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)
    }
}

在上面的代码中,您可以简单地过滤器删除 itemID == nil 的项目。

In the above code you can simply filter out the items with itemID == nil.

这篇关于带有编码器的初始化失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆