【问题标题】:AFNetworking JSON parsing - fails of unknown reasonAFNetworking JSON 解析 - 未知原因失败
【发布时间】:2013-02-25 12:52:09
【问题描述】:

我正在尝试解析一些 JSON。为简单起见,我将使用 github 上的默认示例进行解释: 运行时:

NSURL *url = [NSURL URLWithString:@"http://httpbin.org/ip"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

AFJSONRequestOperation *operation = [AFJSONRequestOperation
JSONRequestOperationWithRequest:request success:^(
    NSURLRequest *request, NSHTTPURLResponse     *response, id JSON) {
    NSLog(@"IP Address: %@", [JSON valueForKeyPath:@"origin"]);
    } failure:nil];

[operation start];

我得到了正确的输出记录。但是,当我将示例的内容(基本上是 1 个元素)复制到 txt 或 html 文件(因此 URLWithString 获取 @"http://my server address/file.txt")时,将其放在我的测试服务器上并尝试从那里赞美,我没有输出。这有什么问题?感谢您的宝贵时间!

(注意:如果我访问 http:// 我的服务器地址 /file.txt 我可以清楚地看到那里的内容,所以这不是问题)

编辑:按照建议,内容是: "{ “起源”:“10.44.119.100” }"

【问题讨论】:

  • 您应该将您复制的确切内容添加到您的问题中,以便人们可以看到它的样子。
  • 感谢 Firoze!尽管可以在 URLWithString 中找到它,但在那里看到它会更好。

标签: objective-c json parsing afnetworking


【解决方案1】:

您的问题可能与您将内容提供为文本文件 (.txt) 而不是 JSON(Content-Type: application.json / .json 扩展名)这一事实有关。 AFNetworking 严格遵守 HTTP 标准,以防止出现意外行为。在您的服务器上设置正确的Content-Type 标头,或者(作为黑客)执行AFJSONRequestOperation +addAcceptableContentTypes: 添加text/plain

作为元注释:在 Stack Overflow 上提问时,细节很重要。如果您发布了您在控制台中看到的错误,那么确定问题所在会容易得多。同样,近似代码不是实际代码;如果您有问题,请具体说明发生了什么。细节很重要。

【讨论】:

    【解决方案2】:

    您应该先对json数据进行编码,然后将其写入文本文件,当您从文件中读取数据时...首先解码数据...

    编辑: 用简单的 http 替换 JSON 操作并检查您是否能够从那里获取数据... 如果你是 JSONOperation 基本上是在寻找不在文本文件中的 json 响应......我猜

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
    
    [operation setUploadProgressBlock:^(NSInteger bytesWritten,long long totalBytesWritten,long long totalBytesExpectedToWrite)
     {
    
         NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
    
     }];
    
    [operation  setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
    {
    
    
        NSString *str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@" Success %@",str);
       // id response = AFJSONDecode(responseObject, nil);
    
        [self requestSucceed:response];
    }
                                      failure:^(AFHTTPRequestOperation *operation, NSError *error)
    {
        NSLog(@"error: %@",  operation.responseString);
    }];
    

    【讨论】:

    • 第一个和第二个位置的数据是一样的,给出为 { "origin": "10.44.119.100" }
    • @Zephyer 我已经编辑了答案...请以这种方式实施,看看你是否得到任何回应。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-21
    • 1970-01-01
    • 2022-10-20
    • 2021-09-01
    相关资源
    最近更新 更多