如何在Swift 4的Decodable协议中使用自定义键?


102

Swift 4通过该Decodable协议引入了对本机JSON编码和解码的支持。如何为此使用自定义键?

例如,说我有一个结构

struct Address:Codable {
    var street:String
    var zip:String
    var city:String
    var state:String
}

我可以将其编码为JSON。

let address = Address(street: "Apple Bay Street", zip: "94608", city: "Emeryville", state: "California")

if let encoded = try? encoder.encode(address) {
    if let json = String(data: encoded, encoding: .utf8) {
        // Print JSON String
        print(json)

        // JSON string is 
           { "state":"California", 
             "street":"Apple Bay Street", 
             "zip":"94608", 
             "city":"Emeryville" 
           }
    }
}

我可以将此编码回一个对象。

    let newAddress: Address = try decoder.decode(Address.self, from: encoded)

但是如果我有一个json对象

{ 
   "state":"California", 
   "street":"Apple Bay Street", 
   "zip_code":"94608", 
   "city":"Emeryville" 
}

我怎么会告诉解码器上Addresszip_code映射到zip?我相信您使用的是新CodingKey协议,但我不知道该如何使用。

Answers:


258

手动自定义编码键

在您的示例中,Codable由于所有属性也都符合,因此您将获得自动生成的符合Codable。这种一致性会自动创建一个仅与属性名称相对应的密钥类型,然后将其用于对单个密钥容器进行编码/解码。

但是,这种自动生成的一致性的一个真正巧妙的功能是,如果您enum在称为“ CodingKeys” 的类型中定义嵌套(或使用typealias具有此名称的a)来符合CodingKey协议,则Swift将自动将用作键类型。因此,这使您可以轻松自定义用于编码/解码属性的键。

因此,这意味着您可以说:

struct Address : Codable {

    var street: String
    var zip: String
    var city: String
    var state: String

    private enum CodingKeys : String, CodingKey {
        case street, zip = "zip_code", city, state
    }
}

枚举案例名称必须与属性名称匹配,并且这些案例的原始值需要与您要编码/解码的键匹配(除非另有指定,否则String枚举的原始值将与案例名称相同)。因此,zip现在将使用key 对属性进行编码/解码"zip_code"

有关自动生成Encodable/ Decodable一致性的确切规则,请参见演进提案(重点是我的):

除了的自动CodingKey需求综合外 enumsEncodableDecodable需求还可以针对某些类型自动综合:

  1. 符合Encodable所有属性的类型将Encodable获得自动生成的,String支持CodingKey枚举的属性映射到案例名称的类型。对于Decodable所有属性都相同的类型也是如此Decodable

  2. 属于(1)的类型CodingKey enumCodingKeystypealiasEncodableDecodable - 以及手动提供类型(名称直接或通过a )将其案例按名称一对一映射到/ 属性的类型 - 使用这些属性和键自动合成init(from:)encode(to:)在适当时进行合成

  3. 落入类型既不(1)也没有(2)将具有如果需要的话提供一个自定义的密钥类型和提供它们自己的init(from:)encode(to:),如适当

编码示例:

import Foundation

let address = Address(street: "Apple Bay Street", zip: "94608",
                      city: "Emeryville", state: "California")

do {
    let encoded = try JSONEncoder().encode(address)
    print(String(decoding: encoded, as: UTF8.self))
} catch {
    print(error)
}
//{"state":"California","street":"Apple Bay Street","zip_code":"94608","city":"Emeryville"}

解码示例:

// using the """ multi-line string literal here, as introduced in SE-0168,
// to avoid escaping the quotation marks
let jsonString = """
{"state":"California","street":"Apple Bay Street","zip_code":"94608","city":"Emeryville"}
"""

do {
    let decoded = try JSONDecoder().decode(Address.self, from: Data(jsonString.utf8))
    print(decoded)
} catch {
    print(error)
}

// Address(street: "Apple Bay Street", zip: "94608",
// city: "Emeryville", state: "California")

属性名称的自动snake_caseJSON键camelCase

在雨燕4.1,如果您重命名zip属性zipCode,你可以利用关键的编码/解码上的策略JSONEncoder,并JSONDecoder以自动转换之间的编码键camelCasesnake_case

编码示例:

import Foundation

struct Address : Codable {
  var street: String
  var zipCode: String
  var city: String
  var state: String
}

let address = Address(street: "Apple Bay Street", zipCode: "94608",
                      city: "Emeryville", state: "California")

do {
  let encoder = JSONEncoder()
  encoder.keyEncodingStrategy = .convertToSnakeCase
  let encoded = try encoder.encode(address)
  print(String(decoding: encoded, as: UTF8.self))
} catch {
  print(error)
}
//{"state":"California","street":"Apple Bay Street","zip_code":"94608","city":"Emeryville"}

解码示例:

let jsonString = """
{"state":"California","street":"Apple Bay Street","zip_code":"94608","city":"Emeryville"}
"""

do {
  let decoder = JSONDecoder()
  decoder.keyDecodingStrategy = .convertFromSnakeCase
  let decoded = try decoder.decode(Address.self, from: Data(jsonString.utf8))
  print(decoded)
} catch {
  print(error)
}

// Address(street: "Apple Bay Street", zipCode: "94608",
// city: "Emeryville", state: "California")

但是,有关此策略的重要注意事项是,它无法使用首字母缩写词或首字母缩写来回荡某些属性名称,根据Swift API设计指南,这些属性名称应统一使用大写或小写(取决于位置) )。

例如,名为的属性someURL将使用键进行编码some_url,但是在解码时,它将转换为someUrl

要解决此问题,您必须手动将该属性的编码键指定为解码器期望的字符串,例如,someUrl在这种情况下(some_url编码器仍将其转换为):

struct S : Codable {

  private enum CodingKeys : String, CodingKey {
    case someURL = "someUrl", someOtherProperty
  }

  var someURL: String
  var someOtherProperty: String
}

(这并不能严格回答您的特定问题,但是鉴于此问答的典型性质,我认为值得考虑)

自定义自动JSON密钥映射

在雨燕4.1,您可以利用自定义按键编码/解码上的策略JSONEncoderJSONDecoder,使您可以提供一个自定义函数映射的编码键。

您提供的函数采用[CodingKey],代表编码/解码中当前点的编码路径(在大多数情况下,您只需要考虑最后一个元素;即当前键)。该函数返回一个CodingKey,它将替换此数组中的最后一个键。

例如,属性名称的UpperCamelCaseJSON键lowerCamelCase

import Foundation

// wrapper to allow us to substitute our mapped string keys.
struct AnyCodingKey : CodingKey {

  var stringValue: String
  var intValue: Int?

  init(_ base: CodingKey) {
    self.init(stringValue: base.stringValue, intValue: base.intValue)
  }

  init(stringValue: String) {
    self.stringValue = stringValue
  }

  init(intValue: Int) {
    self.stringValue = "\(intValue)"
    self.intValue = intValue
  }

  init(stringValue: String, intValue: Int?) {
    self.stringValue = stringValue
    self.intValue = intValue
  }
}

extension JSONEncoder.KeyEncodingStrategy {

  static var convertToUpperCamelCase: JSONEncoder.KeyEncodingStrategy {
    return .custom { codingKeys in

      var key = AnyCodingKey(codingKeys.last!)

      // uppercase first letter
      if let firstChar = key.stringValue.first {
        let i = key.stringValue.startIndex
        key.stringValue.replaceSubrange(
          i ... i, with: String(firstChar).uppercased()
        )
      }
      return key
    }
  }
}

extension JSONDecoder.KeyDecodingStrategy {

  static var convertFromUpperCamelCase: JSONDecoder.KeyDecodingStrategy {
    return .custom { codingKeys in

      var key = AnyCodingKey(codingKeys.last!)

      // lowercase first letter
      if let firstChar = key.stringValue.first {
        let i = key.stringValue.startIndex
        key.stringValue.replaceSubrange(
          i ... i, with: String(firstChar).lowercased()
        )
      }
      return key
    }
  }
}

您现在可以使用以下.convertToUpperCamelCase关键策略进行编码:

let address = Address(street: "Apple Bay Street", zipCode: "94608",
                      city: "Emeryville", state: "California")

do {
  let encoder = JSONEncoder()
  encoder.keyEncodingStrategy = .convertToUpperCamelCase
  let encoded = try encoder.encode(address)
  print(String(decoding: encoded, as: UTF8.self))
} catch {
  print(error)
}
//{"Street":"Apple Bay Street","City":"Emeryville","State":"California","ZipCode":"94608"}

并采用.convertFromUpperCamelCase关键策略进行解码:

let jsonString = """
{"Street":"Apple Bay Street","City":"Emeryville","State":"California","ZipCode":"94608"}
"""

do {
  let decoder = JSONDecoder()
  decoder.keyDecodingStrategy = .convertFromUpperCamelCase
  let decoded = try decoder.decode(Address.self, from: Data(jsonString.utf8))
  print(decoded)
} catch {
  print(error)
}

// Address(street: "Apple Bay Street", zipCode: "94608",
// city: "Emeryville", state: "California")

只是偶然发现了这个自己!我想知道,有没有一种方法可以只覆盖我要更改的一个键,而让其余的单独保留?例如,在案例陈述中,在CodingKeys枚举下;我可以只列出要更改的一个键吗?
chrismanderson

2
"""是用于多行文字:)
Martin R

6
@MartinR甚至只是一行文字而不必转义"s:D
Hamish

1
@chrismanderson正是–特别是考虑到编译器强制要求案例名称与属性名称保持同步(这会给您一个错误,指出您不遵守Codable其他规定)
Hamish

1
@ClayEllis嗯,是的,尽管当然可以直接在初始化程序中使用嵌套容器,例如,这样会Address不必要地使自己解码从父对象图中特定位置开始的JSON对象。将起始密钥路径抽象到解码器本身会更好得多-这是一个粗略的hackey式实现
Hamish

17

使用Swift 4.2,根据您的需要,您可以使用以下3种策略之一,以使模型对象的自定义属性名称与JSON关键字匹配。


#1 使用自定义编码键

使用以下实现声明符合CodableDecodableEncodable协议)的结构时...

struct Address: Codable {
    var street: String
    var zip: String
    var city: String
    var state: String        
}

...编译器自动CodingKey为您生成符合协议的嵌套枚举。

struct Address: Codable {
    var street: String
    var zip: String
    var city: String
    var state: String

    // compiler generated
    private enum CodingKeys: String, CodingKey {
        case street
        case zip
        case city
        case state
    }
}

因此,如果序列化数据格式中使用的键与数据类型中的属性名称不匹配,则可以手动实现此枚举并rawValue为所需情况设置适当的键。

以下示例显示了如何做:

import Foundation

struct Address: Codable {
    var street: String
    var zip: String
    var city: String
    var state: String

    private enum CodingKeys: String, CodingKey {
        case street
        case zip = "zip_code"
        case city
        case state
    }
}

编码(用zip“ zip_code” JSON密钥替换属性):

let address = Address(street: "Apple Bay Street", zip: "94608", city: "Emeryville", state: "California")

let encoder = JSONEncoder()
if let jsonData = try? encoder.encode(address), let jsonString = String(data: jsonData, encoding: .utf8) {
    print(jsonString)
}

/*
 prints:
 {"state":"California","street":"Apple Bay Street","zip_code":"94608","city":"Emeryville"}
 */

解码(用zip属性替换“ zip_code” JSON密钥):

let jsonString = """
{"state":"California","street":"Apple Bay Street","zip_code":"94608","city":"Emeryville"}
"""

let decoder = JSONDecoder()
if let jsonData = jsonString.data(using: .utf8), let address = try? decoder.decode(Address.self, from: jsonData) {
    print(address)
}

/*
 prints:
 Address(street: "Apple Bay Street", zip: "94608", city: "Emeryville", state: "California")
 */

#2。使用蛇案到骆驼案的关键编码策略

如果你的JSON有蛇套管键,你想将它们转换为骆驼套管性能为您的模型对象,你可以设置你JSONEncoderkeyEncodingStrategyJSONDecoderkeyDecodingStrategy属性.convertToSnakeCase

以下示例显示了如何做:

import Foundation

struct Address: Codable {
    var street: String
    var zipCode: String
    var cityName: String
    var state: String
}

编码(将驼峰式属性转换为蛇形JSON密钥):

let address = Address(street: "Apple Bay Street", zipCode: "94608", cityName: "Emeryville", state: "California")

let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
if let jsonData = try? encoder.encode(address), let jsonString = String(data: jsonData, encoding: .utf8) {
    print(jsonString)
}

/*
 prints:
 {"state":"California","street":"Apple Bay Street","zip_code":"94608","city_name":"Emeryville"}
 */

解码(将带蛇纹的JSON密钥转换为驼峰纹的属性):

let jsonString = """
{"state":"California","street":"Apple Bay Street","zip_code":"94608","city_name":"Emeryville"}
"""

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
if let jsonData = jsonString.data(using: .utf8), let address = try? decoder.decode(Address.self, from: jsonData) {
    print(address)
}

/*
 prints:
 Address(street: "Apple Bay Street", zipCode: "94608", cityName: "Emeryville", state: "California")
 */

#3。使用自定义密钥编码策略

如有必要,JSONEncoderJSONDecoder允许您使用JSONEncoder.KeyEncodingStrategy.custom(_:)和设置自定义策略来映射编码键JSONDecoder.KeyDecodingStrategy.custom(_:)

以下示例显示了如何实现它们:

import Foundation

struct Address: Codable {
    var street: String
    var zip: String
    var city: String
    var state: String
}

struct AnyKey: CodingKey {
    var stringValue: String
    var intValue: Int?

    init?(stringValue: String) {
        self.stringValue = stringValue
    }

    init?(intValue: Int) {
        self.stringValue = String(intValue)
        self.intValue = intValue
    }
}

编码(将小写的首字母属性转换为大写的首字母JSON密钥):

let address = Address(street: "Apple Bay Street", zip: "94608", city: "Emeryville", state: "California")

let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .custom({ (keys) -> CodingKey in
    let lastKey = keys.last!
    guard lastKey.intValue == nil else { return lastKey }
    let stringValue = lastKey.stringValue.prefix(1).uppercased() + lastKey.stringValue.dropFirst()
    return AnyKey(stringValue: stringValue)!
})

if let jsonData = try? encoder.encode(address), let jsonString = String(data: jsonData, encoding: .utf8) {
    print(jsonString)
}

/*
 prints:
 {"Zip":"94608","Street":"Apple Bay Street","City":"Emeryville","State":"California"}
 */

解码(将大写的首字母JSON密钥转换为小写的首字母属性):

let jsonString = """
{"State":"California","Street":"Apple Bay Street","Zip":"94608","City":"Emeryville"}
"""

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .custom({ (keys) -> CodingKey in
    let lastKey = keys.last!
    guard lastKey.intValue == nil else { return lastKey }
    let stringValue = lastKey.stringValue.prefix(1).lowercased() + lastKey.stringValue.dropFirst()
    return AnyKey(stringValue: stringValue)!
})

if let jsonData = jsonString.data(using: .utf8), let address = try? decoder.decode(Address.self, from: jsonData) {
    print(address)
}

/*
 prints:
 Address(street: "Apple Bay Street", zip: "94608", city: "Emeryville", state: "California")
 */

资料来源:


3

我所做的就是创建自己的结构,就像您从JSON获得的数据类型一样。

像这样:

struct Track {
let id : Int
let contributingArtistNames:String
let name : String
let albumName :String
let copyrightP:String
let copyrightC:String
let playlistCount:Int
let trackPopularity:Int
let playlistFollowerCount:Int
let artistFollowerCount : Int
let label : String
}

之后,您需要创建具有相同struct扩展名decodableenum结构的扩展名,CodingKey然后需要使用带有其键和数据类型的枚举来初始化解码器(键将来自枚举,数据类型将来临或说出从结构本身引用)

extension Track: Decodable {

    enum TrackCodingKeys: String, CodingKey {
        case id = "id"
        case contributingArtistNames = "primaryArtistsNames"
        case spotifyId = "spotifyId"
        case name = "name"
        case albumName = "albumName"
        case albumImageUrl = "albumImageUrl"
        case copyrightP = "copyrightP"
        case copyrightC = "copyrightC"
        case playlistCount = "playlistCount"
        case trackPopularity = "trackPopularity"
        case playlistFollowerCount = "playlistFollowerCount"
        case artistFollowerCount = "artistFollowers"
        case label = "label"
    }
    init(from decoder: Decoder) throws {
        let trackContainer = try decoder.container(keyedBy: TrackCodingKeys.self)
        if trackContainer.contains(.id){
            id = try trackContainer.decode(Int.self, forKey: .id)
        }else{
            id = 0
        }
        if trackContainer.contains(.contributingArtistNames){
            contributingArtistNames = try trackContainer.decode(String.self, forKey: .contributingArtistNames)
        }else{
            contributingArtistNames = ""
        }
        if trackContainer.contains(.spotifyId){
            spotifyId = try trackContainer.decode(String.self, forKey: .spotifyId)
        }else{
            spotifyId = ""
        }
        if trackContainer.contains(.name){
            name = try trackContainer.decode(String.self, forKey: .name)
        }else{
            name = ""
        }
        if trackContainer.contains(.albumName){
            albumName = try trackContainer.decode(String.self, forKey: .albumName)
        }else{
            albumName = ""
        }
        if trackContainer.contains(.albumImageUrl){
            albumImageUrl = try trackContainer.decode(String.self, forKey: .albumImageUrl)
        }else{
            albumImageUrl = ""
        }
        if trackContainer.contains(.copyrightP){
            copyrightP = try trackContainer.decode(String.self, forKey: .copyrightP)
        }else{
            copyrightP = ""
        }
        if trackContainer.contains(.copyrightC){
                copyrightC = try trackContainer.decode(String.self, forKey: .copyrightC)
        }else{
            copyrightC = ""
        }
        if trackContainer.contains(.playlistCount){
            playlistCount = try trackContainer.decode(Int.self, forKey: .playlistCount)
        }else{
            playlistCount = 0
        }

        if trackContainer.contains(.trackPopularity){
            trackPopularity = try trackContainer.decode(Int.self, forKey: .trackPopularity)
        }else{
            trackPopularity = 0
        }
        if trackContainer.contains(.playlistFollowerCount){
            playlistFollowerCount = try trackContainer.decode(Int.self, forKey: .playlistFollowerCount)
        }else{
            playlistFollowerCount = 0
        }

        if trackContainer.contains(.artistFollowerCount){
            artistFollowerCount = try trackContainer.decode(Int.self, forKey: .artistFollowerCount)
        }else{
            artistFollowerCount = 0
        }
        if trackContainer.contains(.label){
            label = try trackContainer.decode(String.self, forKey: .label)
        }else{
            label = ""
        }
    }
}

您需要在此处根据需要更改每个键和数据类型,并将其与解码器一起使用。


-1

通过使用CodingKey,您可以在可编码或可解码协议中使用自定义密钥。

struct person: Codable {
    var name: String
    var age: Int
    var street: String
    var state: String

    private enum CodingKeys: String, CodingKey {
        case name
        case age
        case street = "Street_name"
        case state
    } }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.