我需要用大写首字母(又名 PascalCase 或 UppperCamelCase)解码 JSON,如下所示:
{
"Title": "example",
"Items": [
"hello",
"world"
]
}
所以我创建了一个符合以下条件的模型Codable
:
struct Model: Codable {
let title: String
let items: [String]
}
But JSONDecoder
会引发错误,因为情况不同。
Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "title", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"title\", intValue: nil) (\"title\").", underlyingError: nil))
我想将模型的属性保留在驼峰命名法中,但我无法更改 JSON 格式。
我发现一个很好的解决方案是创建一个KeyDecodingStrategy https://developer.apple.com/documentation/foundation/jsondecoder/keydecodingstrategy类似于.convertFromSnakeCase https://developer.apple.com/documentation/foundation/jsondecoder/keydecodingstrategy/convertfromsnakecase可在基金会中使用。
extension JSONDecoder.KeyDecodingStrategy {
static var convertFromPascalCase: JSONDecoder.KeyDecodingStrategy {
return .custom { keys -> CodingKey in
// keys array is never empty
let key = keys.last!
// Do not change the key for an array
guard key.intValue == nil else {
return key
}
let codingKeyType = type(of: key)
let newStringValue = key.stringValue.firstCharLowercased()
return codingKeyType.init(stringValue: newStringValue)!
}
}
}
private extension String {
func firstCharLowercased() -> String {
prefix(1).lowercased() + dropFirst()
}
}
它可以像这样轻松使用:
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromPascalCase
let model = try! decoder.decode(Model.self, from: json)
完整示例Gist https://gist.github.com/axelguilmin/087ab9181c5952e4d95920b302ccab25
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)