From 863a9fbbe598e28bf88714ad5f8de285a0fe20bb Mon Sep 17 00:00:00 2001 From: Matt Bruce Date: Wed, 13 Jul 2022 10:26:09 -0500 Subject: [PATCH] added more extension methods Signed-off-by: Matt Bruce --- MVMCore/MVMCore/Models/JSON/JSONValue.swift | 48 ++++++++++++++++++--- 1 file changed, 43 insertions(+), 5 deletions(-) diff --git a/MVMCore/MVMCore/Models/JSON/JSONValue.swift b/MVMCore/MVMCore/Models/JSON/JSONValue.swift index b3527d2..0de0860 100644 --- a/MVMCore/MVMCore/Models/JSON/JSONValue.swift +++ b/MVMCore/MVMCore/Models/JSON/JSONValue.swift @@ -145,17 +145,55 @@ extension JSONValue: ExpressibleByDictionaryLiteral { } } -extension Dictionary where Key == String, Value == Any { - public func toJSONValue() throws -> [String: JSONValue] { +extension Array where Element == Any { + public func toJSONValue() throws -> JSONValue { let data = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted) - return try JSONDecoder().decode([String:JSONValue].self, from: data) + return try JSONDecoder().decode(JSONValue.self, from: data) + } +} + +extension Array where Element == AnyHashable { + public func toJSONValue() throws -> JSONValue { + let data = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted) + return try JSONDecoder().decode(JSONValue.self, from: data) + } +} + +extension Array where Element == JSONValue { + public func toJSONArray() throws -> [Any] { + let encoded = try JSONEncoder().encode(self) + guard let json = try JSONSerialization.jsonObject(with: encoded, options: .mutableContainers) as? [Any] else { + throw JSONValueError.encode + } + return json + } +} + +extension Dictionary where Key == String, Value == Any { + public func toJSONValue() throws -> JSONValue { + let data = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted) + return try JSONDecoder().decode(JSONValue.self, from: data) } } extension Dictionary where Key == String, Value == AnyHashable { - public func toJSONValue() throws -> [String: JSONValue] { + public func toJSONValue() throws -> JSONValue { let data = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted) - return try JSONDecoder().decode([String:JSONValue].self, from: data) + return try JSONDecoder().decode(JSONValue.self, from: data) + } +} + +extension Dictionary where Key == String, Value == Any { + public func toJSONValueDictionary() throws -> JSONValueDictionary { + let data = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted) + return try JSONDecoder().decode(JSONValueDictionary.self, from: data) + } +} + +extension Dictionary where Key == String, Value == AnyHashable { + public func toJSONValueDictionary() throws -> JSONValueDictionary { + let data = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted) + return try JSONDecoder().decode(JSONValueDictionary.self, from: data) } }