Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 4 Codable , CodingKey only for decode

Is it possible that CodingKey can be used for only JSONEncoder and for JSONDecoder use default member names ?

Example I have following structure

var str = """
{
"name": "Endeavor",
"abv": 8.9,
"brewery": "Saint Arnold",
"style": "ipa"
}

"""

enum BeerStyle:String,Codable {
    case ipa
    case stout
    case kolsch
}

struct Beer : Codable {
    let name : String
    let brewery : String
    let style : BeerStyle
    let abv : Float

    // THIS SHOULD BE USED ONLY FOR JSONEncoder ? 
    enum CodingKeys:String,CodingKey {
        case name
        case abv = "alcohol_by_volume"
        case brewery = "brewery_name"
        case style
    }
}

let jsonData = str.data(using: .utf8)!
let decoder = JSONDecoder() // how to to make it not to use Coding key
let beer = try! decoder.decode(Beer.self, from: jsonData)

will not work fine since enum CodingKeys:String,CodingKey is there

Any one can suggest me a idea or link ?

like image 890
Prashant Tukadiya Avatar asked Oct 15 '25 01:10

Prashant Tukadiya


1 Answers

Try this:

  1. Add two enums one for encoding and one for decoding, e.g. EncodingKeys and DecodingKeys
  2. Write custom init(from decoder: Decoder) and encode(to encoder: Encoder) implementations like this.

.

func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: EncodingKeys.self)
    try container.encode(name, forKey: .name)
    // ...
}

and

init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: DecodingKeys.self)
    name = try values.decode(String.self, forKey: .name)
    // ...
}

Update I tried it with just one implementation of encode(...). You just need to rename the Enum to EncodingKeys.self (or something else). Then implement the encode-function like described above. For decoding the CodingKeys and init-function are being synthesized.

like image 105
heyfrank Avatar answered Oct 17 '25 17:10

heyfrank



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!