I have an address type with a property address1
that I'm populating from an API. The API uses snake case and names this property address_1
. I've used CodingKeys to specify the key name, and it creates JSON with the specified key name but doesn't read it.
Is there any way to get a snake case conversion from address_1
to work? How can I tell what key Swift's Decoder is looking for?
import Foundation
struct Address : Codable {
var address1 : String
var city : String
var state : String
var postalCode : String
enum CodingKeys: String, CodingKey {
case address1 = "address_1"
case city, state, postalCode
}
}
var addr = Address(address1: "123 Anywhere Ln", city: "Vero Beach", state: "FL", postalCode: "32968")
let encoder1 = JSONEncoder()
encoder1.keyEncodingStrategy = .convertToSnakeCase
let data1 = try encoder1.encode(addr)
print(String(data: data1, encoding: .utf8)!)
=> {"address_1":"123 Anywhere Ln","state":"FL","city":"Vero Beach","postal_code":"32968"}
let encoder2 = JSONEncoder()
let data2 = try encoder2.encode(addr)
print(String(data: data2, encoding: .utf8)!)
=> {"address_1":"123 Anywhere Ln","state":"FL","city":"Vero Beach","postalCode":"32968"}
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
var addr2 = try decoder.decode(Address.self, from: data1)
print(addr2)
=> Fatal error: Error raised at top level: Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "address_1", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"address_1\", intValue: nil) (\"address_1\").", underlyingError: nil)): file /AppleInternal/BuildRoot/Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-1103.8.25.8/swift/stdlib/public/core/ErrorType.swift, line 200