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 ?
Try this:
EncodingKeys
and DecodingKeys
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With