Graphics Programs Reference
In-Depth Information
JSON Serialization
So far, Nerdfeed deals with XML data only. While XML is nice, it is becoming less popu-
lar, and a new data format called JSON ( JavaScript object notation ) is coming into favor.
Like XML, JSON is a human-readable data interchange format. However, JSON is a lot
more concise, so it takes up less memory and is faster to transfer across networks.
There is a class that deals with JSON in iOS called NSJSONSerialization . This class
can take a chunk of JSON data and turn it into objects. It can also go in the other direction:
take objects and turn them into JSON data. Using this class means you don't have to know
with what JSON really looks like. (But, you should anyway, so be sure to read the section
at the end of this chapter.)
The top songs RSS feed from Apple currently returns XML, but we can ask it to return
JSON instead. Let's do this to get a chance to try out NSJSONSerialization . In
BNRFeedStore.m , change the service URL to request JSON.
- (void)fetchTopSongs:(int)count
withCompletion:(void (^)(RSSChannel *obj, NSError *err))block
{
NSString *requestString = [NSString stringWithFormat:
@"http://itunes.apple.com/us/rss/topsongs/limit=%d/xml", count];
NSString *requestString = [NSString stringWithFormat:
@"http://itunes.apple.com/us/rss/topsongs/limit=%d/json", count];
NSURL *url = [NSURL URLWithString:requestString];
Of course, when this request completes, BNRConnection and RSSChannel will be
pretty confused by this new type of data. Thus, we need to give BNRConnection the
ability to determine whether the data is XML or JSON and parse it appropriately. We also
need to teach RSSChannel and RSSItem how to gather their instance variables from
JSON data.
First, here's how NSJSONSerialization works. When JSON data is received, you
send the message JSONObjectWithData:options:error: to the class
NSJSONSerialization . This method takes the data and returns either an NSArray or
an NSDictionary . Within this dictionary or array, there will be strings, numbers, or
more dictionaries and arrays.
Each dictionary returned from NSJSONSerialization is an instance of NSDiction-
ary and represents a single object within the JSON data. For example, the channel in the
 
Search WWH ::




Custom Search