swift 类型“AllImage”不符合协议“Decodable”/“Encodable”

vlju58qv  于 2023-06-21  发布在  Swift
关注(0)|答案(1)|浏览(124)
struct AllImage: Codable {
    let mediaReferenceID: String?
    let url: String?
    let title: String?
    let description: String?
    let icon: String?
    let tags: [TagInfo]?
    let footerSection: FooterSection?

    enum CodingKeys: String, CodingKey {
        case mediaReferenceID = "media_reference_id"
        case url, title, description, icon
        case ctaInfo = "cta_info"
        case footerSection = "footer_section"
    }
}

这里TagInfoFooterSection也是可编码的,只包含字符串类型。
这个问题有什么解决办法吗?

h7appiyu

h7appiyu1#

CodingKeys应该反映该类型的所有属性,继承Codable,不能有额外的字段。因此,您还应该添加标记并删除ctaInfo。

struct AllImage: Codable {
    let mediaReferenceID: String?
    let url: String?
    let title: String?
    let description: String?
    let icon: String?
    let tags: [TagInfo]?
    let footerSection: FooterSection?

    enum CodingKeys: String, CodingKey {
        case mediaReferenceID = "media_reference_id"
        case url, title, description, icon
        // Commented out this
        // case ctaInfo = "cta_info"
        // Add tags
        case tags = "tags"
        case footerSection = "footer_section"
    }
}

struct TagInfo : Codable {
    
}

struct FooterSection : Codable {
    
}

相关问题