You need to enable JavaScript to run this app. Swift+Moya:如何将JSON中attractions数组解码为Attraction枚举
优惠活动
大模型
产品
解决方案
定价
更多

Swift+Moya:如何将JSON中attractions数组解码为Attraction枚举

问题解答

核心疑问澄清

  1. 如何实现字符串类型Attraction枚举的解码,适配JSON中的attractions字符串数组
  2. Attraction解码逻辑就绪后,现有City模型是否可以完成嵌套数组字段的正常解码

原有实现的问题根源

你之前写的Attraction解码逻辑从容器选型上就出现了场景错配:

  • attractions字段是纯字符串数组,数组内的每个元素是没有键的裸字符串值,并非带键值对结构的字典对象,不需要使用keyedContainer(键容器),也完全不需要自定义嵌套的CodingKeys枚举
  • 现有City模型的CodingKeys存在映射错误:JSON中的字段是country_code,你错误地将countryCode的映射值写成了countryCode,就算attractions逻辑正常,这个字段也会解码失败

分步实现方案

1. 正确实现Attraction枚举的解码

对于原始值为String的枚举,只要枚举case的rawValue和JSON中的字符串完全匹配,编译器会自动生成合规的Decodable实现,不需要手动编写init(from:)方法。
基础可用版本的Attraction枚举实现:

enum Attraction: String, Decodable {
    case cityHall = "CityHall"
    case theatre = "Theatre"
    case port = "Port"
}

如果需要兼容JSON中的异常字符串(比如示例里Leiden城市景点数组中拼写错误的"CItyHall"),才需要手动实现解码逻辑,此时需要使用*单值容器(singleValueContainer)*读取裸字符串,示例代码:

enum Attraction: String, Decodable {
    case cityHall = "CityHall"
    case theatre = "Theatre"
    case port = "Port"

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        // 读取当前数组元素的原始字符串
        let rawValue = try container.decode(String.self)
        // 兼容拼写错误的场景
        let normalizedValue = rawValue == "CItyHall" ? "CityHall" : rawValue
        // 匹配枚举值
        guard let matchedCase = Attraction(rawValue: normalizedValue) else {
            throw DecodingError.dataCorruptedError(
                in: container,
                debugDescription: "未识别的景点字符串:\(rawValue)"
            )
        }
        self = matchedCase
    }
}

2. 修正City模型的解码逻辑

当Attraction正确遵循Decodable协议后,嵌套的[Attraction]数组字段完全可以被系统自动解码——因为数组类型的Decodable实现,本身就依赖数组元素类型的Decodable能力,整个解码链路是完全打通的,不需要为数组写特殊逻辑。
你完全可以移除手写的init(from:)方法,只需要修正CodingKeys的映射、打开注释掉的attractions字段即可:

struct City: Decodable {
  let id: Int
  let name: String
  let countryCode: String
  let attractions: [Attraction]
  let population: Int

  enum CodingKeys: String, CodingKey {
    case id
    case name
    // 正确匹配JSON的下划线键名
    case countryCode = "country_code"
    case attractions
    case population
  }
}

你之前写的Moya调用代码.request(.getCities).map([City].self, atKeyPath: "cities")不需要做任何修改,模型解码逻辑修正后即可正常返回结果。

常见踩坑提醒

  • 容器选型要匹配数据结构:键容器(keyedContainer)仅用于解码带键值对的字典结构,裸值、数组元素这类无键的单值场景,优先使用单值容器(singleValueContainer)
  • 当枚举rawValue和JSON字符串完全匹配时,不要重复手写Decodable实现,编译器自动生成的实现性能和可靠性更高
  • 注意JSON字符串的大小写匹配:未做兼容的情况下,任何大小写不一致的字符都会触发解码失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.25 12:36:02