added helper functions
This commit is contained in:
parent
1dcdc12919
commit
f2d824f829
@ -15,4 +15,47 @@ public enum JSONError: Error {
|
|||||||
case pathNotFound
|
case pathNotFound
|
||||||
case data(path: String)
|
case data(path: String)
|
||||||
case other(error: Error)
|
case other(error: Error)
|
||||||
|
case error(message: String)
|
||||||
|
}
|
||||||
|
|
||||||
|
extension JSONDictionary {
|
||||||
|
|
||||||
|
public func toJSONString(options: JSONSerialization.WritingOptions = []) -> String? {
|
||||||
|
guard let data = try? JSONSerialization.data(withJSONObject: self, options: options),
|
||||||
|
let string = String(data: data, encoding: .utf8) else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return string
|
||||||
|
}
|
||||||
|
|
||||||
|
public func toUrlQueryItems() throws -> [URLQueryItem] {
|
||||||
|
var queryItems: [URLQueryItem] = []
|
||||||
|
for (key, value) in self {
|
||||||
|
var valueString: String
|
||||||
|
if let value = value as? JSONDictionary, let jsonString = value.toJSONString() {
|
||||||
|
valueString = jsonString
|
||||||
|
} else if let value = value as? [AnyHashable], let jsonString = value.toJSONString() {
|
||||||
|
valueString = jsonString
|
||||||
|
} else {
|
||||||
|
guard let baseValueString = String(describing: value.base).removingPercentEncoding else {
|
||||||
|
throw JSONError.error(message: "query item failed: \(key) value \(value.base)")
|
||||||
|
}
|
||||||
|
valueString = baseValueString
|
||||||
|
}
|
||||||
|
let queryItem = URLQueryItem(name: key, value: valueString)
|
||||||
|
queryItems.append(queryItem)
|
||||||
|
}
|
||||||
|
return queryItems
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extension Array where Element == AnyHashable {
|
||||||
|
|
||||||
|
public func toJSONString(options: JSONSerialization.WritingOptions = []) -> String? {
|
||||||
|
guard let data = try? JSONSerialization.data(withJSONObject: self, options: options),
|
||||||
|
let string = String(data: data, encoding: .utf8) else {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return string
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user