繁体   English   中英

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

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

我尝试使用 Swift 4.1 的新功能在 JSON 解码期间将蛇形大小写转换为驼色大小写。

这是示例

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

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

在你的情况下, student_id在JSON密钥将被映射到studentId.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
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM