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

前端 未结 1 470
独厮守ぢ
独厮守ぢ 2020-12-15 22:11

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

Here is the example:

struct StudentInfo: Decodable {
          


        
相关标签:
1条回答
  • 2020-12-15 22:58

    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.

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

    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
      }
    }
    
    0 讨论(0)
提交回复
热议问题