Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to parse large JSON Dictionary in Swift #865

Open
onmyway133 opened this issue Feb 7, 2022 · 0 comments
Open

How to parse large JSON Dictionary in Swift #865

onmyway133 opened this issue Feb 7, 2022 · 0 comments

Comments

@onmyway133
Copy link
Owner

We can define some typealias and build extensions on JSONDictionary to easily extract values

typealias JSONDictionary = [String: Any]
typealias JSONArray = [JSONDictionary]

extension JSONDictionary {
    func dict(_ key: String) -> JSONDictionary? {
        self[key] as? JSONDictionary
    }

    func array(_ key: String) -> JSONArray? {
        self[key] as? JSONArray
    }

    func value<T>(_ key: String, as: T.Type) -> T? {
        self[key] as? T
    }
}


let responseJson = try JSONSerialization.jsonObject(with: data, options: [])

guard
    let responseJson = responseJson as? JSONDictionary,
    let uiAmount = responseJson
        .dict("result")?
        .array("value")?
        .first?
        .dict("account")?
        .dict("data")?
        .dict("parsed")?
        .dict("info")?
        .dict("tokenAmount")?
        .value("uiAmount", as: Double.self)
else { return 0 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant