我正在尝试将我的数据解码为结构。这是我的 JSON 数据结构之一的示例:
{
"name": "abc",
"owner": "bcd",
"fallbackLanguage": "tr",
"localizedValues": {
"en": {
"description": "Lorem Ipsum Dolor Sit Amet"
},
"de": {
"description": "Sed Do Eiusmod Tempor Incididunt"
},
"tr": {
"description": "Consectetur Adipisicing Elit"
}
}
}
这个 JSON 对象的结构是:
struct X {
let name: String
let owner: String
let fallbackLanguage: String
let description: String
}
解码name
,owner
并且fallbackLanguage
不是问题并且已经完成。这是当前CodingKey
和init(from:)
struct CodingKeys: CodingKey {
var stringValue: String
init?(stringValue: String) {
self.stringValue = stringValue
}
var intValue: Int?
init?(intValue: Int) {
self.intValue = intValue
self.stringValue = "\(intValue)"
}
static func makeKey(name: String) -> CodingKeys {
return CodingKeys.init(stringValue: name)!
}
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
owner = try container.decode(String.self, forKey: CodingKeys.makeKey(name: "owner"))
name = try container.decode(String.self, forKey: CodingKeys.makeKey(name: "name"))
fallbackLanguage = try container.decode(String.self, forKey: CodingKeys.makeKey(name: "fallbackLanguage"))
// FIXME: decode localizedValues into `description`
}
问题在于解码description
,因为它保存在多级字典中,并且它的值会因设备区域设置而改变。
在此示例中,如果设备语言环境不是en
,de
或者tr
,它将回退到,tr
因为 fallbackLanguage 是tr
。
任何帮助和建议都会很棒。谢谢你。