json数据格式原生解析器

请求服务器返回数据格式无非就是两种:json和XML,这篇讲解原生如何解析json格式数据

- (void)viewDidLoad
{
    [super viewDidLoad];
	
    _data = [[NSMutableData alloc]init];
    //判断token有没有过期
    NSDate *endDate = [USER_D objectForKey:@"endDate"];
    NSDate *nowDate = [NSDate date];
    //比较现在时间和过去时间  ascend ,上升
    if ([nowDate compare:endDate] == NSOrderedAscending)
    {
        //token没有过期
        FriendsListVC *vc = [[FriendsListVC alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
        [vc release];
    }
    else
    {
        //token过期
    }
}

- (IBAction)login:(UIButton *)sender
{
    NSURL *url = [NSURL URLWithString:@"http://127.0.0.1:8080/st/s"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    NSString *string = [NSString stringWithFormat:@"command=ST_L&name=%@&psw=%@",_nameField.text,_pwdField.text];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [request setHTTPMethod:@"POST"];
    
    NSURLConnection *connetion = [NSURLConnection connectionWithRequest:request delegate:self];
    [connetion start];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"失败:%@",error);
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [_data setData:[NSData data]];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_data appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *string = [[NSString alloc]initWithData:_data encoding:NSUTF8StringEncoding];
    NSLog(@"%@",string);
    NSLog(@"%@",_data);
    
    //NSJSONSerialization JSON解析器
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:_data options:NSJSONReadingMutableContainers error:nil];
    if ([[dic objectForKey:@"result"]integerValue] == 1)
    {
        //登录成功
        //access_token ⽤用户⾝身份验证通过返回的唯⼀一标⽰示⽤用户⾝身份的字段
        //将token保存起来,用于之后调用需要登录验证的接口
        [USER_D setObject:[dic objectForKey:@"access_token" ] forKey:@"token"];
        //计算过期时间
        NSDate *nowDate = [NSDate date];
        //dateByAddingTimeInterval  计算一个时间点加上一段时间后的时间点
        NSDate *endDate = [nowDate dateByAddingTimeInterval:[[dic objectForKey:@"time"] integerValue]];
        //存储过期时间
        [USER_D setObject:endDate forKey:@"endDate"];
        [USER_D synchronize];
        
        FriendsListVC *vc = [[FriendsListVC alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
        [vc release];
    }
    else
    {
        SHOW_ALERT([dic objectForKey:@"error"]);
    }
    
    [string release];
}

- (IBAction)regist:(UIButton *)sender
{
    RegistVC *vc = [[RegistVC alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
    [vc release];
}

可以和XML格式对比一下

XML数据格式原生解析器

你可能感兴趣的:(json数据格式原生解析器)