json解析出错误怎么回事?

2024-10-29 09:41:51
推荐回答(1个)
回答(1):

1. 编码问题。

2. 如果data是有数据的,但是arr是nil,找到error:The operation couldn't be completed. (Cocoa error 3840.)

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];

3. 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:NS