Skip to content

Commit

Permalink
Added a couple of new datatypes for typesafe interactions with JSON d…
Browse files Browse the repository at this point in the history
…ata.
  • Loading branch information
btfranklin committed Jun 17, 2023
1 parent a6cae13 commit 4390192
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
11 changes: 11 additions & 0 deletions Sources/CleverBird/datatypes/JSONType.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Created by B.T. Franklin on 6/15/23

public enum JSONType: String, Codable {
case null
case string
case boolean
case number
case integer
case object
case array
}
52 changes: 52 additions & 0 deletions Sources/CleverBird/datatypes/JSONValue.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Created by B.T. Franklin on 6/15/23

public enum JSONValue: Codable {
case null
case string(String)
case boolean(Bool)
case number(Double)
case integer(Int)
case object([String: JSONValue])
case array([JSONValue])

public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let x = try? container.decode(String.self) {
self = .string(x)
} else if let x = try? container.decode(Bool.self) {
self = .boolean(x)
} else if let x = try? container.decode(Double.self) {
self = .number(x)
} else if let x = try? container.decode(Int.self) {
self = .integer(x)
} else if let x = try? container.decode([String: JSONValue].self) {
self = .object(x)
} else if let x = try? container.decode([JSONValue].self) {
self = .array(x)
} else if container.decodeNil() {
self = .null
} else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Wrong type for JSONValue")
}
}

public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .string(let x):
try container.encode(x)
case .boolean(let x):
try container.encode(x)
case .number(let x):
try container.encode(x)
case .integer(let x):
try container.encode(x)
case .object(let x):
try container.encode(x)
case .array(let x):
try container.encode(x)
case .null:
try container.encodeNil()
}
}
}

0 comments on commit 4390192

Please sign in to comment.