Codable 中单个数据的多个编码键

Multiple coding keys for a single data in Codable

我用的API支持多国语言。例如:

// For Japanese
{
    "earthquake_detail": {
        "advisory_title_ja": "津波注意報",
        "depth_title_ja": "震源深さ",
        "depth_value_ja": "30km",
    }
}

// For English

{
    "earthquake_detail": {
        "advisory_title_en": "Tsunami Advisory",
        "depth_title_en": "Depth",
        "depth_value_en": "30km",       
    }
}

我正在使用 swift codable 将它们映射到结构。有没有办法可以将多个编码键映射到一个变量?这是我的 swift 结构。

struct EarthquakeDetail: Codable {
    var advisoryTitle, depthTitle, depthValue: String?

    enum CodingKeys: String, CodingKey {
        case advisoryTitle = "advisory_title_ja"
        case depthTitle = "depth_title_ja"
        case depthValue = "depth_value_ja"
    }
}

我要获取的是日语,这将是编码键:

enum CodingKeys: String, CodingKey {
            case advisoryTitle = "advisory_title_ja"
            case depthTitle = "depth_title_ja"
            case depthValue = "depth_value_ja"
        }

英语:

enum CodingKeys: String, CodingKey {
            case advisoryTitle = "advisory_title_en"
            case depthTitle = "depth_title_en"
            case depthValue = "depth_value_en"
        }

如果您不打算使用 convertFromSnakeCase 策略,请添加自定义密钥解码策略,从三个编码密钥中删除 _xx

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .custom { codingKeys in
    let lastKey = codingKeys.last!
    if lastKey.intValue != nil || codingKeys.count != 2 { return lastKey }
    if codingKeys.dropLast().last!.stringValue != "earthquake_detail" { return lastKey }
    return AnyCodingKey(stringValue: String(lastKey.stringValue.dropLast(3)))!
}

如果 earthquake_detail 键比 2 级更深,相应地更改 != 2

为了能够创建您需要的自定义编码键

struct AnyCodingKey: CodingKey {
    var stringValue: String
    var intValue: Int?

    init?(stringValue: String) { self.stringValue = stringValue }

    init?(intValue: Int) {
        self.stringValue = String(intValue)
        self.intValue = intValue
    }
}

现声明EarthquakeDetail如下

struct EarthquakeDetail: Codable {
    var advisoryTitle, depthTitle, depthValue: String

    enum CodingKeys: String, CodingKey {
        case advisoryTitle = "advisory_title"
        case depthTitle = "depth_title"
        case depthValue = "depth_value"
    }
}