You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何将含对象数组的JSON响应解析存入Codable的ProductModel

问题解决方法
  • 模型中image_galleries的类型定义错误:JSON返回的image_galleries是对象数组,每个元素包含image_url字符串字段,不是你定义的字典类型[String: [Array<String?>]]
  • 字段名映射错误:JSON中产品ID的字段为id,你模型中定义的是product_id,默认Codable不会自动匹配这两个字段

方案1:使用嵌套模型(推荐)

先定义嵌套的图片项模型:

struct ImageGalleryItem: Codable {
    let image_url: String
}

调整ProductModel,添加CodingKeys显式映射字段:

struct ProductModel: Codable {
    var image_galleries: [ImageGalleryItem]?
    var product_id: String?

    enum CodingKeys: String, CodingKey {
        case image_galleries
        case product_id = "id"
    }
}

解析后可以通过product.image_galleries?.map{$0.image_url}拿到所有图片URL的字符串数组。

方案2:直接解析为字符串数组(无需嵌套模型)

如果你不需要保留嵌套结构,只想直接拿到所有图片URL的数组,可以手动实现解码逻辑:

struct ProductModel: Codable {
    var image_galleries: [String]?
    var product_id: String?

    enum CodingKeys: String, CodingKey {
        case image_galleries
        case product_id = "id"
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        // 先解码为字典数组,再提取所有image_url字段
        let galleryList = try container.decode([[String: String]].self, forKey: .image_galleries)
        image_galleries = galleryList.compactMap { $0["image_url"] }
        product_id = try container.decode(String.self, forKey: .product_id)
    }
}

你之前反馈product_id可以正常取值不符合Codable默认解析规则,大概率是测试过程中临时修改过字段名或JSON结构,显式声明CodingKeys映射可以避免这类隐式问题。

内容的提问来源于stack exchange,提问作者Peter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 00:06:05