【发布时间】:2018-09-27 15:04:35
【问题描述】:
我尝试在 JSON 解码过程中使用 Swift 4.1 的新功能将蛇形大小写转换为骆驼大小写。
这里是example:
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。我错过了什么吗?
【问题讨论】:
-
你想要
case studentID = "studentId"(比较stackoverflow.com/a/44396824/2976878)——解码器在查询编码密钥之前应用密钥策略,因此它将"student_id"转换为"studentId"。 -
谢谢@Hamish!这行得通!
-
@Rob 我有时间会做(如果没有其他人同时发布答案,那就是)
标签: ios swift codable jsondecoder