iOS json解析出错的几种情况总结

iOS json解析出错

对于json格式,我们并不陌生,但是因为它处于不同的语言标准也不一致。分享一下最近项目出现的json问题:

1、编码问题,在不清楚服务端的编码格式的情况下,我直接使用:

NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]]; 
NSError *error = nil; 
NSArray *arr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error]; 

结果发现data是有数据的,但是arr是nil,找到error:The operation couldn't be completed. (Cocoa error 3840.)后来问了一下后台开发,因为存在中文,他采用了GBK编码,通过搜索uft8转gbk找到了答案:

NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]]; 
NSError *error = nil; 
NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000); 
NSString *dataString = [[NSString alloc] initWithData:data encoding:enc]; 
NSData *utf8Data = [dataString dataUsingEncoding:NSUTF8StringEncoding]; 
NSArray *arr = [NSJSONSerialization JSONObjectWithData:utf8Data options:NSJSONReadingMutableContainers error:&error]; 

2、json非标准格式:(比如json数据存在\n \r \t 等制表符)阅读原文

NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]]; 
NSError *error = nil; 
NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000); 
NSString *dataString = [[NSString alloc] initWithData:data encoding:enc]; 
//json数据当中没有 \n \r \t 等制表符,当后台给出有问题时,我们需要对json数据过滤 
 dataString = [dataString stringByReplacingOccurrencesOfString:@"\r\n" withString:@""]; 
 dataString = [dataString stringByReplacingOccurrencesOfString:@"\n" withString:@""]; 
 dataString = [dataString stringByReplacingOccurrencesOfString:@"\t" withString:@""]; 
 
NSData *utf8Data = [dataString dataUsingEncoding:NSUTF8StringEncoding]; 
NSArray *arr = [NSJSONSerialization JSONObjectWithData:utf8Data options:NSJSONReadingMutableContainers error:&error]; <span style="font-family: Arial, Helvetica, sans-serif;"> </span> 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!