onmyway133 / blog

🍁 What you don't know is what you haven't learned
https://onmyway133.com/
MIT License
669 stars 33 forks source link

How to parse large JSON Dictionary in Swift #865

Open onmyway133 opened 2 years ago

onmyway133 commented 2 years ago

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 }