Merge branch 'bugfix/urlQueryParameters' into 'release/9_6_0'
Added helper functions See merge request BPHV_MIPS/mvm_core!192
This commit is contained in:
commit
d3d198b007
@ -8,11 +8,54 @@
|
|||||||
|
|
||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
public typealias JSONArray = [[String: Any]]
|
public typealias JSONArray = [AnyHashable]
|
||||||
public typealias JSONDictionary = [String: AnyHashable]
|
public typealias JSONDictionary = [String: AnyHashable]
|
||||||
|
|
||||||
public enum JSONError: Error {
|
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 = []) throws -> String {
|
||||||
|
let data = try JSONSerialization.data(withJSONObject: self, options: options)
|
||||||
|
guard let string = String(data: data, encoding: .utf8) else {
|
||||||
|
throw JSONError.error(message: "Failed to convert data to string")
|
||||||
|
}
|
||||||
|
return string
|
||||||
|
}
|
||||||
|
|
||||||
|
public func toUrlQueryItems() throws -> [URLQueryItem] {
|
||||||
|
var queryItems: [URLQueryItem] = []
|
||||||
|
for (key, value) in self {
|
||||||
|
var valueString: String
|
||||||
|
if let value = value as? JSONDictionary {
|
||||||
|
valueString = try value.toJSONString()
|
||||||
|
} else if let value = value as? JSONArray {
|
||||||
|
valueString = try value.toJSONString()
|
||||||
|
} 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 JSONArray {
|
||||||
|
|
||||||
|
public func toJSONString(options: JSONSerialization.WritingOptions = []) throws -> String {
|
||||||
|
let data = try JSONSerialization.data(withJSONObject: self, options: options)
|
||||||
|
guard let string = String(data: data, encoding: .utf8) else {
|
||||||
|
throw JSONError.error(message: "Failed to convert data to string")
|
||||||
|
}
|
||||||
|
return string
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user