有一个问题困扰了我两天时间,因为现在要做一个聊天回放功能,需要从接口获取聊天数据并解析。然而接口并没有,所以找后台要了一下聊天数据,得到了一个txt文件。
我尝试把txt文件放到Xcode中解析。
NSString* path = [[NSBundlemainBundle]pathForResource:@"LBChatDemo"ofType:@"json"];
NSData*data = [NSDatadataWithContentsOfFile:path];
NSString*stringdata = [[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];
NSData*contData = [stringdata dataUsingEncoding:NSUTF8StringEncoding];
NSError*myError =nil;
NSDictionary*myData = [NSJSONSerializationJSONObjectWithData:contDataoptions:NSJSONReadingMutableContainerserror:&myError];
然而得到的myData是nil,查看error,内容是
NSDebugDescription=Unescaped control character around character 349.
于是百度,http://bbs.csdn.net/topics/390835989
http://www.cnblogs.com/tanglimei/p/5023937.html
解决原因是,带有空格等不能解析的特殊字符串
NSString*changeString = [stringdatastringByReplacingOccurrencesOfString:@"\t"withString:@""];
changeString = [changeStringstringByReplacingOccurrencesOfString:@"\n"withString:@""];
changeString = [changeStringstringByReplacingOccurrencesOfString:@"\r"withString:@""];
NSData*contData = [changeStringdataUsingEncoding:NSUTF8StringEncoding];
加上一个替换就ok了
对于AF请求下来的数据:http://blog.csdn.net/u011189158/article/details/43022347