JSONparsing错误
我为iOS使用SBJson框架(也称为json-framework)。
parsing某个JSON文件时,出现以下错误: -JSONValue失败。 错误是:未转义的控制字符[0x09] '
我已经使用了这个框架很多次,我也parsing了一个非常类似的JSON文件(甚至更长)在同一个应用程序,它工作正常。
我试着扔了一堆NSLogs,一切似乎都很好。 有人可以指点我这个错误是什么意思,或者至less如何继续debugging这样的错误?
以下是显示错误的代码:
- (void)downloadSchedule:(NSString *)jsonString { // Get JSON feed URL and instantiate a dictionary object with its content NSDictionary *topDic = [jsonString JSONValue]; NSLog(@"topDic count %d", [topDic count]);
topDic显示的计数为0.错误在[jsonString JSONValue]
行。
谢谢
我猜你的文件包含一个未编码的选项卡(ascii 0x09
),应该根据json语法replace为\t
。
我有一个很好的解决scheme。 应用此方法来移除转义字符。
-(NSString *)removeUnescapedCharacter:(NSString *)inputStr { NSCharacterSet *controlChars = [NSCharacterSet controlCharacterSet]; NSRange range = [inputStr rangeOfCharacterFromSet:controlChars]; if (range.location != NSNotFound) { NSMutableString *mutable = [NSMutableString stringWithString:inputStr]; while (range.location != NSNotFound) { [mutable deleteCharactersInRange:range]; range = [mutable rangeOfCharacterFromSet:controlChars]; } return mutable; } return inputStr; }
调用这个方法,像这样传递你的输出string
NSString *output = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"yourUrlString"] encoding:NSUTF8StringEncoding error:nil]; output = [self removeUnescapedCharacter:output];
看看http://www.json.org/有一些字符需要转义才能被JSON正确parsing。 这是原因。 该文件是不正确的JSON。
如果你的文件有'\ n'或'\ r'类的html qoutes,那么它可能会导致obj-c错误。 你可以加 :
[jsonString stringByReplacingOccurrencesOfString:@"\r\n" withString:@"<br />"]
我遇到了同样的问题,并使用它解决。