ios - flickr 无法解析 JSON

标签 ios objective-c iphone flickr afhttprequestoperation

我正在使用 flickr 公共(public) 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])];

最佳答案

您提供了错误的子数据范围。只需更改这一行

NSData *refinedData = [responseObject subdataWithRange:NSMakeRange([@"jsonFlickrFeed(" length], [responseObject length]-([@"jsonFlickrFeed(" length]+1))];

下一行

NSData *refinedData = [responseObject subdataWithRange:NSMakeRange([@"jsonFlickrFeed(" length], ([responseObject length]-1)-([@"jsonFlickrFeed(" length]))];

希望对你有所帮助。

关于ios - flickr 无法解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32116183/

相关文章:

iphone - 根据某些预处理器宏删除静态库

iphone - Objective C - 将 NSString 写入 plist

ios - iOS应用程序不适合iPhone 5屏幕

objective-c - iPhone 上的弹性碰撞

objective-c - 内存 Objective-C 中的 block 在哪里?

ios - 尝试插入非属性值 Objective C

iphone - 设置独立于 TabBar 标题的 NavController 标题

ios - viewDidLoad 从未在子类 UIViewController 中调用

javascript - 使用 PhoneGap/Cordova 时的数据管理/计算

ios - 导航栏上的 UIView 动画有时会出错