JSON is most commonly used as an alternative to XML for RESTful style web services. As such any example that demonstrates anything about JSON must first begin with an example of how to download JSON data.
Let’s begin by creating a method called
stringWithUrl:
that will download data from a specified URL and return the data as an NSString
Now that we have the ability to download the JSON data as a string we are ready to parse the string into an object we can use. What is wonderful about this particular JSON framework is that it can parse JSON into a collection of
NSDictionary
and NSArray
objects which are amazingly simple to deal with.Combined with the
stringWithUrl:
method above, we are now ready to use the JSON framework to create another method that will parse the JSON string into an Object …NOTE: The method above returns
id
because the actual object type can vary between anNSDictionary
and an NSArray
.Now let’s put this to use! First, consider a real example of a JSON feed. Here is a sample of what a public feed from Jaiku looks like:
Here is an how we would use the above methods to download the public feed from Jaiku and cast it to an
NSDictionary
…At this point we have everything we need to query any aspect of the feed. For example here is how you might query the “title” field:
Notice in the sample Jaiku feed there is a value “stream” that is actually a list of objects. This is an example of how an
NSArray
is created to contain a list of object in JSON. Although the JSON frameworks creates the array, you will still need to cast it from a generic ‘id’ type into an NSArray before you can use it safely. Here is an example of how we would query the array of objects and handle each object in the array…Conclusions
As you can see, working with JSON feeds are much simpler than XML feeds. There is no cumbersome parser you have to create; and getting values from the JSON object is as simple as working with an NSDictionary or NSArray. If only more Web Service APIs used JSON the world would be a better place!
NOTE: For those that are interested, there are many handy ways to convert XML into JSON on the server side. To find out more, take a look at the official JSON.org website. I’ve used the Java JSON library to convert XML feeds into JSON more times than I can count!
No comments:
Post a Comment