Skip to content

Instantly share code, notes, and snippets.

@szotp
Created June 27, 2019 15:52
Show Gist options
  • Save szotp/2cf18b6ea91de115038e96d8a5dccc23 to your computer and use it in GitHub Desktop.
Save szotp/2cf18b6ea91de115038e96d8a5dccc23 to your computer and use it in GitHub Desktop.
Parsing weird jsons in swift with Codable
import Foundation
struct StringCodingKey: CodingKey {
let stringValue: String
init?(stringValue: String) {
self.stringValue = stringValue
}
var intValue: Int? {
return nil
}
init?(intValue: Int) {
assertionFailure()
return nil
}
}
struct KeyedBox<T: Codable>: Codable {
var key: String
var value: T
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: StringCodingKey.self)
let key = container.allKeys[0]
self.key = key.stringValue
self.value = try container.decode(T.self, forKey: key)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: StringCodingKey.self)
try container.encode(value, forKey: StringCodingKey(stringValue: key)!)
}
}
let json = """
{
"hello" : "world"
}
"""
let data = json.data(using: .utf8)!
let decoder = JSONDecoder()
let parsed = try! decoder.decode(KeyedBox<String>.self, from: data)
print(parsed)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment