代码之家  ›  专栏  ›  技术社区  ›  Damo

KeyedDecodingContainer始终没有密钥

  •  0
  • Damo  · 技术社区  · 8 年前

    编辑: 解决方案

    感谢@LeoDabus下面的回答——为了让我的代码正常工作,我对ImageKey的声明做了如下更改:

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

    原始问题

    我试图实现一个可解码的结构,图像。图像非常简单,看起来像:

    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 回复  |  直到 8 年前