From 05a549c633ada07e71b73bc33f240680f425f4b3 Mon Sep 17 00:00:00 2001 From: Matt Bruce Date: Fri, 24 Jun 2022 09:01:37 -0500 Subject: [PATCH 1/2] added toJSONArray Signed-off-by: Matt Bruce --- MVMCore/MVMCore/Models/Extensions/Encoder.swift | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/MVMCore/MVMCore/Models/Extensions/Encoder.swift b/MVMCore/MVMCore/Models/Extensions/Encoder.swift index 9f50bc3..832059b 100644 --- a/MVMCore/MVMCore/Models/Extensions/Encoder.swift +++ b/MVMCore/MVMCore/Models/Extensions/Encoder.swift @@ -34,6 +34,15 @@ extension Encodable { return jsonAny } + public func toJSONArray() throws -> [Any] { + let data = try self.encode() + let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) + guard let jsonArray = json as? [Any] else { + throw JSONError.error(message: "JSON Array not found") + } + return jsonArray + } + public func toJSONString() -> String? { guard let json = self.toJSON(), let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted), From acf5aae880ce686547a6939acfc399dfa5958352 Mon Sep 17 00:00:00 2001 From: Matt Bruce Date: Fri, 24 Jun 2022 09:57:34 -0500 Subject: [PATCH 2/2] added JSONValue additions Signed-off-by: Matt Bruce --- MVMCore/MVMCore/Models/JSON/JSONValue.swift | 33 +++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/MVMCore/MVMCore/Models/JSON/JSONValue.swift b/MVMCore/MVMCore/Models/JSON/JSONValue.swift index 333fc91..b3527d2 100644 --- a/MVMCore/MVMCore/Models/JSON/JSONValue.swift +++ b/MVMCore/MVMCore/Models/JSON/JSONValue.swift @@ -13,6 +13,7 @@ public typealias JSONValueDictionary = [String: JSONValue] public enum JSONValueError: Error { case encode + case TypeMismatch } extension Optional { @@ -68,6 +69,38 @@ public enum JSONValue: Codable, Equatable { case .null: break } } + + public var base: Any { + switch self { + case .string(let string): return string + case .int(let int): return int + case .double(let double): return double + case .bool(let bool): return bool + case .object(let object): return try! object.toJSONAny() + case .array(let array): return try! array.toJSONArray() + case .null: return NSNull() + } + } + + public func value() throws -> T { + guard let base = self.base as? T else { + throw JSONValueError.TypeMismatch + } + return base + } + + private func value(type: T.Type) throws -> T { + let base: T = try value() + return base + } + + public func toString() throws -> String { try value(type: String.self) } + public func toDouble() throws -> Double { try value(type: Double.self) } + public func toInt() throws -> Int { try value(type: Int.self) } + public func toBool() throws -> Bool { try value(type: Bool.self) } + public func toArray(of type: T.Type) throws -> [T]{ try value(type: [T].self) } + public func toObject(of type: T.Type) throws -> T { try value(type: T.self) } + } public func ==(lhs: JSONValue, rhs: JSONValue) -> Bool {