简体   繁体   中英

How do I call a subclass in an API result?

When I am trying to call an API in swift, how can I access the subclass?

{
    "country": {
        "bar": "australia",
        "bar2": "melbourne"
    },

}

I know with regular API calls you use jsonResult["country"] as AnyObject? as? String jsonResult["country"] as AnyObject? as? String jsonResult["country"] as AnyObject? as? String however I am getting nil when doing that because I assume I am not calling "bar", just "country" which contains both "bar" and "bar2".

What is the syntax to do this? I have tried ["country"]["bar"], ["country.bar"] etc.

You may checkout https://github.com/SwiftyJSON/SwiftyJSON

Then you may use it like this:

if let bar = jsonResult["country"]["bar"].string{
    // get bar now
} else {
    // no result
}

BTW, if you tend to use default Swift library, you may do like this:

if let country = jsonResult["country"] as? [String: AnyObject]{
    if let bar = country["bar"] as? String {
        // get bar now
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM