JSON解析错误
问题描述:
我正在为iOS使用SBJson框架(也称为json-framework)。JSON解析错误
解析某个JSON文件时,出现以下错误: -JSONValue失败。错误是:未转义的控制字符[0x09]'
我已经多次使用此框架,并且我也在同一个应用程序中解析了非常类似的JSON文件(甚至更长),它工作正常。
我试着扔了一堆NSLogs,一切似乎都很好。有人能告诉我这个错误是什么意思,或者至少该如何继续调试这样的错误?
这里是一个显示错误的代码:
- (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]
线。
谢谢
答
我有一个很好的解决方案。应用此方法来移除转义字符。
-(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;
}
调用此方法与通过你的输出字符串这样
NSString *output = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"yourUrlString"] encoding:NSUTF8StringEncoding error:nil];
output = [self removeUnescapedCharacter:output];
答
如果你的文件是有“\ n”或“\ r”之类的HTML qoutes的则可能在obj-导致错误C。 您可以添加:
[jsonString stringByReplacingOccurrencesOfString:@"\r\n" withString:@"<br />"]
我有同样的问题,解决了用这个。
请编辑您的答案并格式化代码以使其可读。 – kleopatra
否。正确的解决方案是修复无效JSON的来源,而不是用这样的黑客来解决它。 –
但是对于有效的JSON,我们可以在PHP和I-Phone端修复它,以实现更安全的JSON解析。 – chandan