Skip to content

Instantly share code, notes, and snippets.

@amosavian
Created February 9, 2019 19:58
Show Gist options
  • Save amosavian/0bb027306adf0caa44396a56cf9da1ef to your computer and use it in GitHub Desktop.
Save amosavian/0bb027306adf0caa44396a56cf9da1ef to your computer and use it in GitHub Desktop.
struct Bill: Codable {
let b: String
let c: String
}
struct B2: Codable {
enum CodingKeys: String, CodingKey { case a }
let bill: Bill
let a: Int
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.bill = try Bill(from: decoder)
self.a = try container.decode(Int.self, forKey: .a)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try bill.encode(to: encoder)
try container.encode(a, forKey: .a)
}
}
let json = """
{
"b": "Hello",
"c": "World",
"a": 1
}
""".data(using: .utf8)!
let dec = JSONDecoder()
var h = try! dec.decode(B2.self, from: json)
print(h)
let encoder = JSONEncoder()
let nj = try! encoder.encode(h)
print(String(data: nj, encoding: .utf8)!)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment