Summary of several cases of iOS json parsing error

  • 2021-09-24 23:52:12
  • OfStack

Error in iOS json parsing

We are no strangers to the json format, but because it is in different language standards, it is not the same. Share json problems in recent projects under 1:

1. Coding problem. I use it directly when I don't know the coding format of the server:


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

The results showed that data had data, but arr was nil, and found error: The operation couldn 't be completed. (Cocoa error 3840.) Later, he asked for a background development. Because of the existence of Chinese, he used GBK coding and found the answer by searching uft 8 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\ n\ r\ t and other tabs) 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]; 
//json There is no data in the data  \n \r \t  Wait for tabs, when there is a problem in the background, we need to json Data filtering  
 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, hope to help everyone, thank you for your support to this site!


Related articles: