Skip to content

Instantly share code, notes, and snippets.

@sho-ito-1027
Last active January 22, 2018 08:38
Show Gist options
  • Save sho-ito-1027/a3b6fea8cde8a107b0cb88a7106692d5 to your computer and use it in GitHub Desktop.
Save sho-ito-1027/a3b6fea8cde8a107b0cb88a7106692d5 to your computer and use it in GitHub Desktop.
JSONと異なる形でDecodeしたい場合、`init(from decoder: Decoder) throws`を実装
import Foundation
struct Response: Decodable {
let main: Main
struct Main: Decodable {
let sub: Sub
struct Sub: Decodable {
let a: UInt
let b: String
enum Keys: String, CodingKey {
case a
case b
}
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Sub.Keys.self)
// 一旦文字列として取得
let a = try container.decode(UInt.self, forKey: .a)
let b = try container.decode(String.self, forKey: .b)
self.sub = Sub.init(a: a, b: b)
}
}
private enum Keys: String, CodingKey {
case main
}
}
let json = """
{
"main": {
"a": 10,
"b": "Hoge",
}
}
""".data(using: .utf8)!
let res = try JSONDecoder().decode(Response.self, from: json)
print(res.main.sub.a) // 10
print(res.main.sub.b) // Hoge
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment