先把錯誤原文貼出來:
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn't be completed. (Cocoa error 3840.)" (Unescaped control character around character 1419.) UserInfo=0x1563cdd0 {NSDebugDescription=Unescaped control character around character 1419.}
關鍵字是 Unescaped control character——「未跳脫的控制字元」。標準 JSON 字串裡不允許直接出現 \n、\r、\t 這類控制字元。
之前的介面都是規範格式,從沒出過問題。今天卻時好時壞,貼到線上 JSON 驗證器也說沒錯。折騰半天才發現罪魁禍首就是這些制表符。既然收到資料後才發現,那就只能在解析前先清洗掉。
NSString *responseString = [request responseString];
responseString = [responseString stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];
responseString = [responseString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
responseString = [responseString stringByReplacingOccurrencesOfString:@"\t" withString:@""];
NSLog(@"responseString = %@", responseString);
SBJsonParser *parser = [[[SBJsonParser alloc] init] autorelease];
id returnObject = [parser objectWithString:responseString];
NSDictionary *userInfo = nil;
NSArray *userArr = nil;
if ([returnObject isKindOfClass:[NSDictionary class]]) {
if (userInfo) {
[userArr release];
}
userInfo = (NSDictionary *)returnObject;
} else if ([returnObject isKindOfClass:[NSArray class]]) {
userArr = (NSArray *)returnObject;
}
NSError *e = nil;
若使用系統內建的解析方式,同樣要先清洗:
NSDictionary *userInfo = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:&e];
if (e) {
NSLog(@"%@", e);
}
因為多數線上驗證器會先對輸入做正規化,把控制字元自動轉義或移除,而 NSJSONSerialization 是照標準嚴格把關的。
更根本的解法,是請後端在輸出 JSON 時正確跳脫這些字元(\n 應輸出為 \\n),而不是靠用戶端各自打補丁。否則同一份資料換到 Android 或 Web 端,又會再爆一次同樣的問題。