added base:Any? as the JSON Value property

Signed-off-by: Matt Bruce <matt.bruce@verizon.com>
This commit is contained in:
Matt Bruce 2022-01-25 13:57:23 -06:00
parent b63e60e58a
commit 875abb11e9
2 changed files with 26 additions and 0 deletions

View File

@ -25,6 +25,11 @@ extension Encodable {
return (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)).flatMap { $0 as? JSONDictionary }
}
public func toJSONAny() -> [String: Any]? {
guard let data = try? self.encode() else { return nil }
return (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)).flatMap { $0 as? [String: Any] }
}
public func toJSONString() -> String? {
guard let json = self.toJSON(),
let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted),

View File

@ -68,6 +68,27 @@ 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 object.toJSONAny()
case .array(let array): return ["array": array].toJSONAny()?["array"]
case .null: return nil
}
}
public func value<T>() -> T? { self.base as? T }
public func toString() -> String? { self.base as? String }
public func toDouble() -> Double? { self.base as? Double }
public func toInt() -> Int? { self.base as? Int }
public func toBool() -> Bool? { self.base as? Bool }
public func toArray<T>(of type: T.Type) -> [T]?{ self.base as? [T] }
public func toObject<T>(of type: T.Type) -> T? { self.base as? T }
}
public func ==(lhs: JSONValue, rhs: JSONValue) -> Bool {