diff --git a/SwiftyJSONModel/JSONObject.swift b/SwiftyJSONModel/JSONObject.swift index 43c113e..6d72639 100644 --- a/SwiftyJSONModel/JSONObject.swift +++ b/SwiftyJSONModel/JSONObject.swift @@ -87,15 +87,7 @@ public extension JSONObject where PropertyType.RawValue == String { } private func value(for keyPath: [PropertyType]) throws -> [T] { - return try value(for: keyPath) { - try $0.arrayValue().lazy.enumerated().map({ index, json in - do { - return try T(json: json) - } catch let error as JSONModelError { - throw JSONModelError.invalidValueFor(key: String(index), error) - } - }) - } + return try value(for: keyPath) { try Array(json: $0) } } // MARK: - Value for keypath - Dictionary @@ -104,17 +96,7 @@ public extension JSONObject where PropertyType.RawValue == String { } private func value(for keyPath: [PropertyType]) throws -> [String: T] { - return try value(for: keyPath) { - var result: [String: T] = [:] - try $0.dictionaryValue().forEach({ key, json in - do { - result[key] = try T(json: json) - } catch let error as JSONModelError { - throw JSONModelError.invalidValueFor(key: key, error) - } - }) - return result - } + return try value(for: keyPath) { try Dictionary(json: $0) } } // MARK: - Value for keypath - Date diff --git a/SwiftyJSONModel/JSONTypes.swift b/SwiftyJSONModel/JSONTypes.swift index 4ce45f0..6799eb3 100644 --- a/SwiftyJSONModel/JSONTypes.swift +++ b/SwiftyJSONModel/JSONTypes.swift @@ -102,6 +102,18 @@ public extension Array where Element: JSONRepresentable { } } +public extension Array where Element: JSONInitializable { + public init(json: JSON) throws { + self = try json.arrayValue().lazy.enumerated().map({ index, json in + do { + return try Element(json: json) + } catch let error as JSONModelError { + throw JSONModelError.invalidValueFor(key: String(index), error) + } + }) + } +} + struct JSONDict: JSONRepresentable { let dict: [String: T] @@ -122,6 +134,20 @@ public extension Dictionary where Key == String, Value: JSONRepresentable { } } +public extension Dictionary where Key == String, Value: JSONInitializable { + public init(json: JSON) throws { + var result: [String: Value] = [:] + try json.dictionaryValue().forEach({ key, json in + do { + result[key] = try Value(json: json) + } catch let error as JSONModelError { + throw JSONModelError.invalidValueFor(key: key, error) + } + }) + self = result + } +} + public extension Date { public func json(with transformer: DateTransformer) -> String { return transformer.string(form: self)