我们发送请求后,一般会获得data数据,这个时候我们反序列化即可。
常用的数据格式之一是JSON,格式如:
{key:value,key:value,key:value....}(1)因为iOS5之前苹果不支持JSON解析,所以催生很多第三方解析,SBJson以及JSONKit。简单地JSON反序列化示例如下:
NSURL *url=[NSURL URLWithString:@"http://www.baidu.com"];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
WPUser *user=[[WPUser alloc]init];
//数据对象的属性名最好是数据库中返回的dict中的key
[user setValuesForKeysWithDictionary:dict];
NSLog(@"%@,%@",user.userName,user.userPwd);typedef NS_OPTIONS(NSUInteger, NSJSONReadingOptions) {
NSJSONReadingMutableContainers = (1UL << 0), //根节点可变
NSJSONReadingMutableLeaves = (1UL << 1), //子节点可变
NSJSONReadingAllowFragments = (1UL << 2) //一般默认时只反序列化NSArray和NSDictionary
} NS_ENUM_AVAILABLE(10_7, 5_0);//测试根节点是什么类型 id dict=[NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]; NSLog(@"%@",dict); id dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:NULL]; NSLog(@"%@",dict); id dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:NULL]; NSLog(@"%@",dict); id dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:NULL]; NSLog(@"%@",dict);
(2)使用setValuesForKeysWithDictionary时,属性尽量用NSNumber代替NSInteger等。因为有可能登录失败等原因,数据是空。
(3)NSInteger会判断系统是64位时用long类型,32位系统时用int类型,所以我们在拼接字符串时,如果用%d,那么在64位下会出现问题,反之用%ld在32位下会出现问题。解决办法是强制转化(int)之类的,或者避免使用NSInteger。
(4)一般项目中都会重写description方法。
-(NSString *)description{
return [];
}//url里面有中文字符或者空格%20等特殊字符时需要转义
NSString *str=@"我是 MT";
NSString *newStr=[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@",newStr);
//反转义
NSString *oldStr=[newStr stringByRemovingPercentEncoding];
NSLog(@"%@",oldStr);%E6%88%91%E6%98%AF%20MT 我是 MT
如果要更新UI,需要在主线程中,一下有两种方法。这种错误最常见,经常会忘记在主线程中更新UI。
建议:尽量使用GCD,因为GCD还有很多API,而NSOperation相对简单。
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError) {
NSLog(@"%@",connectionError.localizedDescription);
//弹框等都属于更新UI,需要在主线程中
//因为NSOperation是基于GCD开发的,所以以下的GCD使用完全没问题
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"错误" message:@"错误内容" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
});
//方法二:当然也可以使用NSOperation的
[[NSOperationQueue mainQueue]addOperationWithBlock:^{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"错误" message:@"错误内容" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
}];
}else{
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
WPUser *user=[[WPUser alloc]init];
//数据对象的属性名最好是数据库中返回的dict中的key
[user setValuesForKeysWithDictionary:dict];
NSLog(@"%@,%@",user.userName,user.userPwd);
}
}];//虽然下面请求很方便,没有很多步骤的url和request等,但最大的问题是,下面的请求是同步的,会阻塞
NSData *imgData=[NSData dataWithContentsOfURL:url];NSURLRequest *request1=[NSURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:10];
(8)如果用户名或者密码错误,即做一个判断,然后在主线程中更新UI,弹框或者其他形式提示用户。
这里的判断,可以用user,userId等等属性判断,看是否有返回数据,如果没有返回数据,说明没有登录成功。
常用的数据格式之二:XML
(1)解析方法在手机上一般是SAX(Simple API for XML),它只读不能修改,速度快。而在PC服务器上一般DOM(Document Object Modal),它可读可修改,但速度慢。
(2)SAX解析的具体类是NSAMLParser。
(3)真正XML解析是用的是<NSXMLParserDelegate>的几个代理方法,分别在几个方法中实现自己。
//开始解析文档的时候,可初始化一些数据
-(void)parserDidStartDocument:(NSXMLParser *)parser{
if (!self.userArrayM) {
self.userArrayM=[NSMutableArray array];
}else{
[self.userArrayM removeAllObjects];//清空内容,不要实例化创建
}
if (!self.contentM) {
self.contentM=[NSMutableString string];
}else{
[self.contentM setString:@""];//不能用nil,用了nil就能相当于又实例化了一次,此处只要清空即可
}
}
//找到那个节点,新建一个对象
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
if ([elementName isEqualToString:@"User"]) {
self.user=[[WPUser alloc]init];
//如果有属性,也可设置属性
self.user.userId=attributeDict[@"userId"];
}
//没开始一个新节点的时候都要清空内容,以防来回被拼接
[self.contentM setString:@""];
}
//找到那个节点里面的内容,会多次调用,拼接内容
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
//拼接字符串
[self.contentM appendString:string];
}
//结束那个节点
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
/*用如下方法一个一个判断
if ([elementName isEqualToString:@"userName"]) {
self.user.userName=self.contentM;
}else if ([elementName isEqualToString:@"userPwd"]){
self.user.userPwd=self.contentM;
}……
*/
//用如下KVC方法
if ([elementName isEqualToString:@"user"]) {
[self.userArrayM addObject:self.user];
}else if (![elementName isEqualToString:@"users"]){
[self.user setValue:self.contentM forKey:elementName];
}
}
//结束解析
-(void)parserDidEndDocument:(NSXMLParser *)parser{
}备注:
(1)在iOS开发中,用一个可变数组给不可变数组赋值,尽量使用copy,养成良好习惯:
self.array1=[self.arrayM copy];
详细可见:enumerateObjectsUsingBlock 、for 、for(... in ...) 的区别 & 性能测试
【iOS开发-95】JSON反序列化、XML数据解析以及主线程中的UI更新等小细节
原文:http://blog.csdn.net/weisubao/article/details/42026127