JSON
JSON copied to clipboard
Automatically decode key paths?
Would it make sense for this project to add the ability to decode key paths? I wanted to discuss it first before making a PR. Or maybe someone has a better implementation.
Given the json
{"error":{"code":401, "message":"unauthorized"}}
Then get the code with
let statusCode: Int = try decode(json, key: "error.code")
Something like this:
/// Generically decode an value from a given JSON dictionary.
///
/// - parameter dictionary: a JSON dictionary
/// - parameter key: key in the dictionary
/// - returns: The expected value
/// - throws: JSONDeserializationError
public func decode<T>(_ dictionary: JSONDictionary, key: String) throws -> T {
// decode key paths in the format of "first.second.third"
if key.contains(".") {
var keys = key.components(separatedBy: ".")
let firstKey = keys.removeFirst()
guard let second = dictionary[firstKey] as? JSONDictionary else {
throw JSONDeserializationError.invalidAttribute(key: firstKey)
}
return try decode(second, key: keys.joined(separator: "."))
}
guard let value = dictionary[key] else {
throw JSONDeserializationError.missingAttribute(key: key)
}
guard let attribute = value as? T else {
throw JSONDeserializationError.invalidAttributeType(key: key, expectedType: T.self, receivedValue: value)
}
return attribute
}