`convertFromSnakeCase`策略不适用于Swift中的自定义`CodingKeys` [英] The `convertFromSnakeCase` strategy doesn't work with custom `CodingKeys` in Swift

查看:248
本文介绍了`convertFromSnakeCase`策略不适用于Swift中的自定义`CodingKeys`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用Swift 4.1的新功能在JSON解码期间将蛇形格式转换为camelCase.

I try to use Swift 4.1's new feature to convert snake-case to camelCase during JSON decoding.

这是示例:

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.我想念什么吗?

I need provide custom CodingKeys since the convertFromSnakeCase strategy can't infer capitalization for acronyms or initialisms (such as studentID) but I expect the convertFromSnakeCase strategy will still work for testScore. However, the decoder throws error ("No value associated with key CodingKeys") and it seems that I can't use convertFromSnakeCase strategy and custom CodingKeys at the same time. Am I missing something?

推荐答案

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

The key strategies for JSONDecoder (and JSONEncoder) are applied to all keys in the payload – including those that you provide a custom coding key for. When decoding, the JSON key will first be mapped using the given key strategy, and then the decoder will consult the CodingKeys for the given type being decoded.

在您的情况下,JSON中的student_id密钥将由.convertFromSnakeCase映射到studentId.转换的确切算法是在文档中提供的:

In your case, the student_id key in your JSON will be mapped to studentId by .convertFromSnakeCase. The exact algorithm for the transformation is given in the documentation:

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

  1. Capitalize each word that follows an underscore.

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

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

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

Combine the words into a single string.

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

The following examples show the result of applying this strategy:

fee_fi_fo_fum

   转换为:feeFiFoFum

    Converts to: feeFiFoFum

feeFiFoFum

   转换为:feeFiFoFum

    Converts to: feeFiFoFum

base_uri

   转换为:baseUri

    Converts to: baseUri

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

You therefore need to update your CodingKeys to match this:

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
  }
}

这篇关于`convertFromSnakeCase`策略不适用于Swift中的自定义`CodingKeys`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆