我正在使用flickr公共API,我遇到了解析JSON的问题。这是我的代码。
NSString *urlString = @"https://api.flickr.com/services/feeds/photos_public.gne?format=json";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
// operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//(JSON text did not start with array or object and option to allow fragments not set.)
NSString *rawString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSData *refinedData = [responseObject subdataWithRange:NSMakeRange([@"jsonFlickrFeed(" length], [responseObject length]-([@"jsonFlickrFeed(" length]+1))];
NSError *parseError = nil;
NSDictionary *jsonObject=[NSJSONSerialization
JSONObjectWithData:refinedData
options:NSJSONReadingMutableLeaves
error:&parseError];
NSError *parsingError = nil;
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
[operation start];
解析时出错:
Error Domain=NSCocoaErrorDomain Code=3840 "The data couldn’t be read because it isn’t in the correct format." (Invalid escape sequence around character 15901.) UserInfo=0x7fa613da71c0 {NSDebugDescription=Invalid escape sequence around character 15901.}
解析时是否需要指定任何特定的字符集?
由于API响应不在我的控制范围内,因此需要在我的最后完成所需的更改。
解决方案: @ vishnuvaran的猜测在逻辑上是正确的,除此之外,我们需要逃避" \'"这个角色然后我才能解析JSON。
[requiredString replaceOccurrencesOfString:@"\\\'" withString:@" " options:NSLiteralSearch range:NSMakeRange(0, [requiredString length])];
答案 0 :(得分:1)
您提供了错误的子数据范围。只需更改此行
NSData *refinedData = [responseObject subdataWithRange:NSMakeRange([@"jsonFlickrFeed(" length], [responseObject length]-([@"jsonFlickrFeed(" length]+1))];
到下面的行
NSData *refinedData = [responseObject subdataWithRange:NSMakeRange([@"jsonFlickrFeed(" length], ([responseObject length]-1)-([@"jsonFlickrFeed(" length]))];
希望它会对你有所帮助。