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 > </span>
感激閱讀,希望能協助到大家,謝謝大家對本站的支持!
【iOS json解析出錯的幾種狀況總結】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!