AFNetworking JSON解析 - 未知原因失败

时间:2013-02-25 12:52:09

标签: objective-c json parsing afnetworking

我试图解析一些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://我的服务器地址/file.txt”)时,将它放在我的测试服务器上并尝试从那里开始,我没有输出。这有什么问题?谢谢你的时间!

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

编辑:根据建议,内容为: “{   “origin”:“10.44.119.100” }“

2 个答案:

答案 0 :(得分:1)

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

作为一个元注释:在Stack Overflow上提问时,细节很重要。如果您发布了在控制台中看到的错误,则可以更轻松地确定问题所在。同样,近似代码不是实际代码;如果您遇到问题,请具体说明发生了什么。细节很重要。

答案 1 :(得分:-1)

您应首先对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);
}];