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>
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!