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) } }