Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Parsing multi-level JSON

Hi. I wonder if anyone can help with parsing some JSON in Swift. At one level deep I am fine, but I have the following output and cannot get it parsed.

{
    "Categories":
    [
        {
            "Accountants":
            [
                {"name":"Company name 1","address": "Address for company 1"},
                {"name":"Company name 2","address": "Address for company 2"}
            ]
        },
        {
            "Builders":
            [
                {"name":"Company name 1","address": "Address for company 1"},
                {"name":"Company name 2","address": "Address for company 2"}
            ]
        },
        {
            "Dry Cleaners":
            [
                {"name":"Company name 1","address": "Address for company 1"},
                {"name":"Company name 2","address": "Address for company 2"}
            ]
        }
    ]
}

What I would like is a tableview that shows the categories, i.e.

+Accountants +Builders +Dry Cleaners

Then, once clicked go to another tableview with the section's listings. I'm failing at the first hurdle of trying to parse the categories!

Any advice greatly appreciated. Here is my code so far:

        class Category: NSObject {
            var title: String?
        }

        var categories: [Category]? = []

        // This line fetches the data shown as JSON above
        let urlRequest = URLRequest(url: URL(string: "http://localhost/listing.php")!)

        let task = URLSession.shared.dataTask(with: urlRequest){ (data,response,error) in
            if error != nil {
                print(error!)
                return
            }
            self.categories = [Category]()
            do {
                let json = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
                if let categoriesFromJson = json["Categories"] as? [[String : AnyObject]] {
                    // This print line outputs ALL of the JSON, but I cannot work out how to parse the categories
                    print(categoriesFromJson)
                }
            } catch let error {
                print(error)
            }
        }
        task.resume()