Parsing the JSON objects in iphone using the default framework which was provided in ios5.
this framework is very simple to implement.
The response from the sample json is the string, arrays or Json objects.
The typical thing is the code changes based on the type of out put we get with the json.
The json response may be an array or string or a dictionary. so based on that we should perform the coding.
the following code replicates the json parsing.
//write this part of code in viewdidload:
// h ah i have taken the url from the android tutorial
NSString *url=[NSString stringWithFormat:@"http://api.androidhive.info/contacts/"];
//getting the contents of url into data
NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
//using nsjsonserialisation
//the below part of code is used to take data fron NSData object and converts into string,
nsarray,NSDictionary based on options NSJSONReadingMutableContainers then it returns the NSArray or NSDictionary
//if the options NSJSONReadingMutableContainers then it returns nsarray or dictioanry or if
NSDictionary *jsonse=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"json response %@",jsonse);
NSArray *subarr=[jsonse objectForKey:@"contacts"];
NSLog(@"subarray %@",subarr);
for (NSDictionary *d in subarr) {
[names addObject:[d objectForKey:@"phone"]];
NSLog(@"names %@",names);
for (NSDictionary *numbers in names) {
NSLog(@"%@",[numbers objectForKey:@"mobile"]);
} }
No comments:
Post a Comment