More developers and users are using JSON to distribute and acquire data from the Internet. iOS Developers often need to access JSON data and there is a built-in NSJSONSerialization class to retrieve JSON data from an accessible source.
Retrieving JSON data is one thing, putting it to use is another. In looking through Google for examples I found that most of the solutions offered dealt with a very simple JSON data structure of only one-level deep of information. Immediately the question arises how to deal with more complex JSON data structures.
[Update 09/03/12]: I added a new Core Data and JSON Tutorial with source code.
This Xcode 4.3.2 and iOS 5.1.1 app is one way to see the approach I took. I used arrays and dictionaries as a way to manipulate the small JSON file. I offer it as an Xcode 4.3.2 project with the source code so you can see how it works under the hood.
The project folder contains the source code and project document along with a sample JSON file and a folder of two .png images. I included the text and images in case you want to put them on your own web server to test. If you do, you’ll need to update the #define statements to reference the new urls. For this project I already have those items hosted on one of Newbound Inc’s., Amazon Server and the app draws from their associated urls.
When you run the app in Xcode’s 5.1 Simulator, it will appear as an iPad app in landscape orientation. You can rotate the device, but I think it works better in landscape mode.
The Split-View displays a TableView using a custom row header in a grouped style table. Clicking on a row, displays the detail information on the related DetailView.
It’s the source code that’s the most interesting because it shows one way to read a three-level deep JSON file and parse it into different objects and accumulate them into an array of dictionaries containing an array of dictionaries. Seeing how to parse a three-level JSON file means you can handle a n-level JSON file if the need ever arises.
The example shows how to create a custom header using the Grouped Table Style incorporating an image. There are adequate comments in the code to offer insights. There are a number of commented-out NSLog statements you may uncomment to provide feedback in the console during program execution. The image when shown in the DetailView will animate using blocks with a typedef. I learned that coding technique from the excellent NSScreencasts paid sessions.
The example is not a complete app. The received JSON data is not stored. It is meant as a teaching tool to teach the aspects I’ve described above. There are other ways to accomplish receiving JSON data and manipulating that into useful information using other collection types. Other features desired are left as an exercise for the user. 😉
I have included the Xcode 4.3.2 and iOS 5.1.1 project here just in case you want to examine and run the completed application using the iPad Simulator.