Chaim Friedman
Chaim Friedman

Reputation: 720

Swift nested Json

I have a url that outputs a Json list of buses.

{"buses":
[
{"time_id”:"56555","bustime":"10:00 AM","price":"30.00","group_id":"1234"},
{"time_id":"56525",”bustime":"11:00 AM","price":"40.00","group_id":"1235"}
]}

The following has always worked for me to retrieve each bus as so:

let url = NSURL(string: "https://www.json_output_url.com:")

    if let JSONData = NSData(contentsOfURL: url!)
    {
        if let json = (try? NSJSONSerialization.JSONObjectWithData(JSONData, options: [])) as? NSDictionary
        {
            if let BusArray = json["buses"] as? [NSDictionary]
            {
                for item in BusArray
                {

Now, the output has changed and the Buses array is nested in an outer array as so:

{"results":[
{"buses":
[
{"time_id”:"56555","bustime":"10:00 AM","price":"30.00","group_id":"1234"},
{"time_id":"56525",”bustime":"11:00 AM","price":"40.00","group_id":"1235"}
]}
]}

And I can no longer retrieve the Buses array because it is nested. I don't want to use a library such as Swiftyjson or anything, I just want to adjust my simple code to be able to retrieve stuff in a lower hierarchy. How is this achieved?

Upvotes: 1

Views: 304

Answers (2)

Eric Aya
Eric Aya

Reputation: 70097

Note: I suppose you're using NSData(contentsOfURL:) for tests purposes. Be careful to use an asynchronous method instead in your real app.

Here's the safe way to decode your new JSON data:

if let url = NSURL(string: "https://www.json_output_url.com:"),
        JSONData = NSData(contentsOfURL: url),
        json = try? NSJSONSerialization.JSONObjectWithData(JSONData, options: []),
        dict = json as? [String: AnyObject],
        results = dict["results"] as? [[String: AnyObject]] {
    for result in results {
        if let buses = result["buses"] as? [[String: String]] {
            for bus in buses {
                print(bus)
                if let time = bus["bustime"] {
                    print("Time: \(time)")
                }
            }
        }
    }
}

Upvotes: 1

Andrej
Andrej

Reputation: 7416

EDITED2 answer:

if let BusArray = json["buses"] as? [[String: AnyObject]] // downcast to array of NSDictionary
{
    for item in BusArray
    {
        let timeId = item["time_id"] as? String
        let bustime = item["bustime"] as? String
        : 

Upvotes: 1

Related Questions