我尝试在 JSON 解码期间使用 Swift 4.1 的新功能将蛇形大小写转换为驼峰形大小写。
这是示例:
struct StudentInfo: Decodable {
internal let studentID: String
internal let name: String
internal let testScore: String
private enum CodingKeys: String, CodingKey {
case studentID = "student_id"
case name
case testScore
}
}
let jsonString = """
{"student_id":"123","name":"Apple Bay Street","test_score":"94608"}
"""
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let decoded = try decoder.decode(StudentInfo.self, from: Data(jsonString.utf8))
print(decoded)
} catch {
print(error)
}
我需要提供自定义CodingKeys
,因为该convertFromSnakeCase
策略无法推断首字母缩写词或首字母缩写词(例如studentID
)的大写,但我希望该convertFromSnakeCase
策略仍然适用于testScore
. 但是,解码器抛出错误(“没有与键 CodingKeys 关联的值”),似乎我不能同时使用convertFromSnakeCase
策略和自定义CodingKeys
。我错过了什么吗?