Working with JSON in IOS

Source: Internet
Author: User
Tags tojson

Note from Author:this are a learning note of working with JSON on IOS 5 Tutorial written by Ray Wenderlich.

JSON is a simple human readable format, is often used to send data over a newtork connection.

For instance, if you had a Pet object with member variables name, breed, and age, the JSON representation would simply is :

{"Name": "Dusty", "Breed": "Poodle", "Age": 7}

The reason JSON is important are many third parties such as Google, Yahoo, or Kiva make Web services that return JSON Formatted data when you visit a URL with a specified query string.

Parsing JSON from the Web

First, we need to download the JSON data from the Web, which would implement with GCD to avoid blocking the main thread as This process is usually time-consuming.

1 #defineKbgqueue dispatch_get_global_queue (dispatch_queue_priority_default, 0)2 #defineKlatestkivaloansurl [Nsurl urlwithstring:@ "http://api.kivaws.org/v1/loans/search.json?status=fundraising "]3 4Dispatch_async (Kbgqueue, ^5 {6nsdata* data =[NSData Datawithcontentsofurl:klatestkivaloansurl];7 [Self performselectoronmainthread: @selector (fetcheddata:)8 Withobject:data9 Waituntildone:yes];Ten});

In our case, the JSON file is relatively small so we ' re going to do the parsing inside Fetcheddata:on the main thread. If you ' re parsing large JSON feeds (which are often the case), being sure to does that in the background.

1- (void) Fetcheddata: (NSData *) ResponseData2 {3     //parse out the JSON data4Nserror *error;5Nsdictionary *json =[Nsjsonserialization jsonobjectwithdata:responsedata6 options:kniloptions7error:&ERROR];8Nsarray *latestloans = [JSON objectforkey:@"Loans"];9NSLog (@"Loans:%@", Latestloans);Ten}

nsjsonserialization has a static method called JSONObjectWithData:options:error This takes an nsdata an D gives you back a Foundation object–usually an nsdictionary or an nsarray depending what does you have at the top of the Your JSON file hierarchy.

Parsing Options

Kniloptions is just a constant for 0. Here is the list of available options:

    • nsjsonreadingmutablecontainers

The arrays and dictionaries created'll be mutable. Good if you want to add things to the containers after parsing it.

    • Nsjsonreadingmutableleaves

The leaves (i.e. the values inside the arrays and dictionaries) would be mutable. Good if you want to modify the strings read in, etc.

    • Nsjsonreadingallowfragments

Parses out the top-level objects that is not arrays or dictionaries.

So, if you ' re isn't only reading, but also modifying the data structure from your JSON file, pass the appropriate options fr Om the list above to JSONObjectWithData:options:error:.

Generating JSON Data

Here we ll build a nsdictionary called info where we store the loan information as who, where, and what in different keys and values.

//build a Info object and convert to JSONNsdictionary *info = [Nsdictionary dictionarywithobjectsandkeys:loan[@"name"],@"W.H.O.", [(Nsdictionary*) loan[" Location"][@"Country"],@"where", @ (outstandingamount),@" What", nil];//Convert object to DataNSData *jsondata =[Nsjsonserialization datawithjsonobject:info OPTIONS:NSJSONWRITINGP rettyprinted Error:&error];

nsjsonwritingprettyprinted -If want to send the JSON over the Internet to a server with Kniloptions as this W Ill generate compact JSON code, and if you want to see the JSON use nsjsonwritingprettyprinted as this would format it nice Ly.

Integrating Objects and JSON

In fact, for convenience, we can use the category to extend nsdictionary, nsarray, nsstring, and nsdata with methods to convert to and from JSON data.

@interfacensdictionary (jsoncategories)+ (Nsdictionary *) dictionarywithcontentsofjsonurlstring: (NSString *) urladdress;-(NSData *) ToJSON;@end @implementationnsdictionary (jsoncategories)+ (Nsdictionary *) dictionarywithcontentsofjsonurlstring: (NSString *) urladdress{NSData* data =[NSData Datawithcontentsofurl:[nsurl urlwithstring:urladdress]; __autoreleasing Nserror* ERROR =Nil; IDresult =[nsjsonserialization jsonobjectwithdata:data options:kniloptions Erro R:&ERROR]; if(Error! = nil)returnNil; returnresult;} -(NSData *) tojson{Nserror* ERROR =Nil; IDresult = [Nsjsonserialization datawithjsonobject:self options:kniloptions error:&ERROR]; if(Error! = nil)returnNil; returnresult; }@end

So with this category fetching JSON from the web becomes as easy as:

Nsdictionary  MyInfo = [nsdictionary dictionarywithcontentsofjsonurlstring:@ "http://www.yahoo.com /news.json"];

And of course on any of your Nsdictionary objects your can do:

 nsdictionary* information = [nsdictionary dictionarywithobjectsandkeys:@ "  orange   ",  apple  " ,  banana  " , @ " fig  "   *json = [information ToJSON]; 

Pretty cool and readable code. Now of course you can also extend nsmutabledictionary with the same dictionarywithcontentsofjsonurlstring: method, but the there you'll have the to pass nsjsonreadingmutablecontainers as Options–so Hey, nsmutablediction Ary could is initialized with JSON too, and it ' ll hold mutable data.

Working with JSON in IOS

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.