20

我尝试在 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。我错过了什么吗?

4

1 回答 1

35

JSONDecoder( 和)的键策略JSONEncoder适用于有效负载中的所有键 - 包括您为其提供自定义编码键的键。解码时,首先使用给定的密钥策略映射 JSON 密钥,然后解码器将查询CodingKeys正在解码的给定类型。

在您的情况下,student_id您的 JSON 中的键将映射到studentIdby .convertFromSnakeCase文档中给出了转换的确切算法:

  1. 将下划线后面的每个单词大写。

  2. 删除所有不在字符串开头或结尾的下划线。

  3. 将单词组合成一个字符串。

以下示例显示了应用此策略的结果:

fee_fi_fo_fum

    转换为:feeFiFoFum

feeFiFoFum

    转换为:feeFiFoFum

base_uri

    转换为:baseUri

因此,您需要更新您的CodingKeys以匹配此:

internal struct StudentInfo: Decodable, Equatable {
  internal let studentID: String
  internal let name: String
  internal let testScore: String

  private enum CodingKeys: String, CodingKey {
    case studentID = "studentId"
    case name
    case testScore
  }
}
于 2018-04-17T23:26:56.557 回答