-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added a couple of new datatypes for typesafe interactions with JSON d…
…ata.
- Loading branch information
1 parent
a6cae13
commit 4390192
Showing
2 changed files
with
63 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | ||
} | ||
} | ||
} |