iOS請求的json資料解析錯誤問題解決

weixin_34326429發表於2017-05-23

請求伺服器,返回的json資料有時候會解析錯誤,可能是因為伺服器返回的json資料摻有轉義字元等導致的解析失敗,解決方法如下:

NSData *data = responseObject;
NSString *dataStr =  [[NSString alloc]initWithData: data encoding:NSUTF8StringEncoding];
        
NSString * treatedStr = [dataStr stringByReplacingOccurrencesOfString:@"\t" withString:@""];
treatedStr = [treatedStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
treatedStr = [treatedStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];
treatedStr = [treatedStr stringByReplacingOccurrencesOfString:@"\\" withString:@""];
NSData *jsonData = [treatedStr dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *object = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];

相關文章