Skip to content
This repository was archived by the owner on Aug 24, 2019. It is now read-only.
This repository was archived by the owner on Aug 24, 2019. It is now read-only.

Automatically decode key paths? #6

@nickdomenicali

Description

@nickdomenicali

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
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions