Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@bricker
Last active April 5, 2021 06:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bricker/143f8d77986e2da14a1d91bd55a46093 to your computer and use it in GitHub Desktop.
Save bricker/143f8d77986e2da14a1d91bd55a46093 to your computer and use it in GitHub Desktop.
public enum JSONValue {
case object([String: JSONValue])
case array([JSONValue])
case string(String)
case number(Double)
case boolean(Bool)
case null
public var value: JSONPrimitive? {
switch self {
case .object(let value): return value
case .array(let value): return value
case .string(let value): return value
case .number(let value): return value
case .boolean(let value): return value
case .null: return nil
}
}
}
extension JSONValue: Decodable {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let value = try? container.decode(Bool.self) {
self = .boolean(value)
} else if let value = try? container.decode(Double.self) {
// Double covers Int as well
self = .number(value)
} else if let value = try? container.decode(String.self) {
self = .string(value)
} else if let value = try? container.decode([JSONValue].self) {
self = .array(value)
} else if let value = try? container.decode([String: JSONValue].self) {
self = .object(value)
} else {
self = .null
}
}
}
extension JSONValue: Encodable {
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .object(let value): try container.encode(value)
case .array(let value): try container.encode(value)
case .string(let value): try container.encode(value)
case .number(let value): try container.encode(value)
case .boolean(let value): try container.encode(value)
case .null: try container.encodeNil()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment