`convertFromSnakeCase` 策略不适用于 Swift 中的自定义 `CodingKeys`

The `convertFromSnakeCase` strategy doesn't work with custom `CodingKeys` in Swift

我尝试使用 Swift 4.1 的新功能在 JSON 解码期间将 snake-case 转换为 camelCase。

这里是 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 仍然有效。但是,解码器会抛出错误 ("No value associated with key CodingKeys"),而且我似乎无法同时使用 convertFromSnakeCase 策略和自定义 CodingKeys。我错过了什么吗?

JSONDecoder(和 JSONEncoder)的密钥策略适用于负载中的所有密钥——包括您为其提供自定义编码密钥的密钥。解码时,JSON 密钥将首先使用给定的密钥策略进行映射,然后解码器将参考 CodingKeys 来解码给定的类型。

在您的情况下,JSON 中的 student_id 键将被 .convertFromSnakeCase 映射到 studentId。转换的确切算法是 given in the documentation:

  1. Capitalize each word that follows an underscore.

  2. Remove all underscores that aren't at the very start or end of the string.

  3. Combine the words into a single string.

The following examples show the result of applying this strategy:

fee_fi_fo_fum

    Converts to: feeFiFoFum

feeFiFoFum

    Converts to: feeFiFoFum

base_uri

    Converts to: 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
  }
}