我使用的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"
}发布于 2020-03-26 13:55:42
如果您不打算使用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"
}
}https://stackoverflow.com/questions/60861011
复制相似问题