【问题标题】:flickr not able to parse JSONflickr 无法解析 JSON
【发布时间】:2015-08-20 10:46:42
【问题描述】:

我正在使用 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])];

【问题讨论】:

  • 检查您的 json 响应,因为您的 json 格式不正确。

标签: ios objective-c iphone flickr afhttprequestoperation


【解决方案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]))];

希望对你有所帮助。

【讨论】:

  • 除了上述行之外,我也没有改变任何东西。
  • @Vishnuvardhan 它的动态数据,每次该 url 发送不同的结果。我试过你的逻辑,有时它起作用,有时它不起作用。可能是因为某些字符阻止我们进行解析。是否需要使用任何特定的编码?
  • @ajay 我不认为这是因为编码。我完全相信这是由于子数据范围造成的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-20
相关资源
最近更新 更多