SoFunction
Updated on 2025-04-04

Summary of several situations of errors in iOS json parsing

iOS json parsing error

We are not unfamiliar with json format, but it is not consistent because it is in different language standards. Share the json problem that occurred in the recent project:

1. Coding problem. If I don’t know the encoding format of the server, I use it directly:

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

It turned out that data has data, but arr is nil, and error:The operation couldn't be completed. (Cocoa error 3840.) Later, I asked about the background development. Because of the Chinese, he used GBK encoding and found the answer by searching for uft8 to 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 non-standard format: (for example, json data exists, etc. tab characters)Read the original text

NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]]; 
NSError *error = nil; 
NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000); 
NSString *dataString = [[NSString alloc] initWithData:data encoding:enc]; 
//There are no tab characters such as \n \r \t in the json data. When there is a problem with the background, we need to filter the json data. 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> 

Thank you for reading, I hope it can help you. Thank you for your support for this site!