我使用的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",
}
}
我正在使用快速编码将它们映射到结构。有没有一种方法可以将多个编码键映射到单个变量?这是我的快速结构。
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"
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句