ios JSON 解析流程(转)
转自:http://blog.csdn.net/linzhiji/article/details/6833884
.h文件
#import <UIKit/UIKit.h> #import "JSONKit.h" @interface MainViewController : UIViewController { UIButton *btn; } @end
.m文件
// // MainViewController.m // testapple // // Created by kiri on 12-5-8. // Copyright (c) 2012年 __MyCompanyName__. All rights reserved. // #import "MainViewController.h" @implementation MainViewController #pragma mark - View lifecycle // Implement loadView to create a view hierarchy programmatically, without using a nib. - (void)loadView { [super loadView]; self.navigationController.navigationBar.hidden = NO; self.title = @"测试"; btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 40)]; [btn setBackgroundImage:[UIImage imageNamed:@"btnoff.png"] forState:UIControlStateNormal]; [btn setBackgroundImage:[UIImage imageNamed:@"btnon.png"] forState:UIControlStateHighlighted]; [btn addTarget:self action:@selector(onbuttonclick) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btn]; } // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; } -(void)onbuttonclick { NSLog(@"onbuttonclick"); NSString *jsonstring = @"[{\"age\":18,\"book\":{\"price\":23.2,\"title\":\"booooooook1\"},\"name\":\"samyou\"},{\"age\":22,\"book\":{\"price\":21,\"title\":\"booooooook2\"},\"name\":\"samsam\"}]"; NSData *data = [jsonstring dataUsingEncoding:NSUTF8StringEncoding]; NSArray *arr = (NSArray *)[data mutableObjectFromJSONData]; NSLog(@"count=%d",arr.count); for(int i=0;i<arr.count;i++) { NSDictionary *people = [arr objectAtIndex:i]; NSString *name = [people objectForKey:@"name"]; NSNumber *age = [people objectForKey:@"age"]; NSLog(@"person withname=%@,age = %d",name,[age intValue]); NSDictionary *book = [people objectForKey:@"book"]; NSString *bookname = [book objectForKey:@"title"]; NSNumber *price = [book objectForKey:@"price"]; NSLog(@"book with title=%@, price=%f",bookname,[price doubleValue]); } } -(void)dealloc { [btn release]; [super dealloc]; } @end
点击按钮得出的结果
2012-09-21 14:26:33.763 testapple[2922:c07] onbuttonclick
2012-09-21 14:26:33.764 testapple[2922:c07] count=2
2012-09-21 14:26:33.764 testapple[2922:c07] person withname=samyou,age = 18
2012-09-21 14:26:33.764 testapple[2922:c07] book with title=booooooook1, price=23.200000
2012-09-21 14:26:33.765 testapple[2922:c07] person withname=samsam,age = 22
2012-09-21 14:26:33.765 testapple[2922:c07] book with title=booooooook2, price=21.000000