JSON 作为一种轻量级的数据交换格式,应用于互联网各处,下文将展示利用IOS自带的JSON解析方法,进行JSON数据解析,代码 如下所示:
// ViewController.h // Copyright © 2016年 www.maomao365.com. All rights reserved. #import@interface ViewController : UIViewController { UITextView * _uiTextViewTest; UITextField * _uiTextField; } @end // ViewController.m // Created by shenye on 16/4/21. // Copyright © 2016年 www.maomao365.com All rights reserved. // #import "ViewController.h" @interface ViewController () @end @implementation ViewController //按钮事件 -(void)btnClick:(id)sender{ _uiTextViewTest.text =@"准备解析web地址"; if([_uiTextField.text isEqual:@""]){ _uiTextViewTest.text = @"当前web地址不能为空!"; return; } if(![_uiTextField.text indexOfAccessibilityElement:@"http"]){ _uiTextViewTest.text = @"不是合法的web地址"; return; } [self showJsonInfoByWebAdd];//解析JSON } //解析JSON方法 -(void)showJsonInfoByWebAdd{ NSError *error; //加载一个NSURL对象 NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:_uiTextField.text]]; //将请求的url数据放到NSData对象中 NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; //IOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error]; NSDictionary *info = [dic objectForKey:@"weatherinfo"]; _uiTextViewTest.text = [NSString stringWithFormat:@"城市 %@ 气温: %@ 风向: %@ 最后检测时间:%@",[info objectForKey:@"city"],[info objectForKey:@"temp"],[info objectForKey:@"WD"], [info objectForKey:@"time"] ]; } - (void)viewDidLoad { [super viewDidLoad]; //JSON解析 示例 start //生成界面 UITextView *uiTextViewTest = [[UITextView alloc]initWithFrame:CGRectMake(20,20, self.view.frame.size.width-30, 300)]; uiTextViewTest.layer.borderColor = [[UIColor grayColor]CGColor]; uiTextViewTest.layer.borderWidth = 2.0f; [self.view addSubview:uiTextViewTest]; _uiTextViewTest = uiTextViewTest; UILabel *uiLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, 350, 100, 30)]; [uiLabel setText:@"web地址:"]; [self.view addSubview:uiLabel]; UITextField *uiTextField = [[UITextField alloc]initWithFrame:CGRectMake(100, 350, self.view.frame.size.width-110, 30)]; uiTextField.layer.borderColor =[[UIColor grayColor] CGColor]; uiTextField.layer.borderWidth = 2.0f; uiTextField.text =@"http://www.weather.com.cn/data/sk/101010100.html"; [self.view addSubview:uiTextField]; _uiTextField = uiTextField; UIButton *button1 = [[UIButton alloc]initWithFrame:CGRectMake(30,400, 150, 50)]; [button1 setBackgroundColor:[UIColor grayColor]]; [button1 setTitle:@"解析JSON" forState:UIControlStateNormal]; [button1 addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchDown]; [self.view addSubview:button1]; //JSON解析 示例 end return; }
运行效果如下图所示: