KeyedDecodingContainer始终具有零键

时间:2018-06-07 10:33:17

标签: ios json swift decodable

编辑:解决方案

感谢下面的@LeoDabus'回答 - 为了使我的代码工作,我改变了我的ImageKey声明,如下所示:

extension Image {
    enum ImageKey: String, CodingKey {
        case width = "Width"
        case height = "Height"
        case url = "Url"
    }
}

原始问题

我正在尝试实现一个Decodable结构,Image。图像看起来非常简单:

struct Image : Decodable {
    let width: CGFloat
    let height: CGFloat
    let url: String
}

当然,当我试图解析json时,我收到的没有成员变量被设置。所以我进一步调查,发现我的解码器总是没有键。以下是我一直使用的按键:

enum ImageKey: String, CodingKey {
    case width = "width"
    case height = "height"
    case url = "url"
}

我尝试过没有显式实例化的密钥,例如:

enum ImageKey: String, CodingKey {
    case width
    case height
    case url
}

同样的结果。

这是解码器的初始化:

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

    width = try container.decodeIfPresent(CGFloat.self, forKey: .width) ?? 0.0

    height = try container.decodeIfPresent(CGFloat.self, forKey: .height) ?? 0.0

    url = try container.decodeIfPresent(String.self, forKey: .url) ?? ""
}

当我在init方法中放置断点并检查容器时,它看起来像:

inspecting container

在我看来,容器应该有键(宽度,高度,URL),但是没有,这就是解码器永远找不到任何东西的合理原因。

以下是我正在测试的json示例,我想知道大写是否有助于/阻碍:

{
    "Width": 800,
    "Height": 590,
    "Url": "https://obfuscated.image.url/image.jpg"
}

有没有人见过这个?知道为什么容器有零键?

感谢阅读,并一如既往地感谢任何帮助。

0 个答案:

没有答案