Skip to content

Instantly share code, notes, and snippets.

@mattyoung
Last active February 22, 2021 21:33
Show Gist options
  • Save mattyoung/356ddbdbd25767a7dc269df0265b76c1 to your computer and use it in GitHub Desktop.
Save mattyoung/356ddbdbd25767a7dc269df0265b76c1 to your computer and use it in GitHub Desktop.
import Foundation
struct SomeObject: Codable {
let name: String
}
struct OtherObject: Codable {
let number: Int
}
let data = """
[{
"type": "first",
"name": "Test"
}, {
"type": "second",
"number": 10
}]
""".data(using: .utf8)!
enum TargetEnum: Codable {
case first(SomeObject)
case second(OtherObject)
enum CodingKeys: CodingKey {
case type
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let type = try container.decode(String.self, forKey: .type)
switch type {
case "first":
try self = .first(SomeObject(from: decoder))
case "second":
try self = .second(OtherObject(from: decoder))
default:
let context = DecodingError.Context(codingPath: decoder.codingPath,
debugDescription: "Unexpected type: \(type)")
throw DecodingError.dataCorrupted(context)
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case .first(let obj):
try container.encode("first", forKey: .type)
try obj.encode(to: encoder)
case .second(let obj):
try container.encode("second", forKey: .type)
try obj.encode(to: encoder)
}
}
}
print("================ decode ===================")
let decoded = try! JSONDecoder().decode([TargetEnum].self, from: data)
print(decoded)
/* OUTPUT:
[__lldb_expr_66.TargetEnum.first(__lldb_expr_66.SomeObject(name: "Test")),
__lldb_expr_66.TargetEnum.second(__lldb_expr_66.OtherObject(number: 10))]
*/
print("\n\n---------------- encode -------------------")
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let encoded = try! encoder.encode(decoded)
print(String(decoding: encoded, as: UTF8.self))
// https://www.hackingwithswift.com/example-code/language/how-to-format-json-using-codable-and-pretty-printing
print("\nDone")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment