2013-02-25 97 views
-1

即时尝试解析一些JSON。运行时, :为了简单解释生病利用在github上的默认实例AFNetworking JSON解析 - 未知原因失败

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我能看到的内容有清楚所以这不是问题)

编辑:作为建议,内容是: “ { “原点”:“10.44.119.100” }”

+0

您应该将复制到您问题中的确切内容添加到您的问题中,以便人们可以看到看起来像什么。 – 2013-02-25 13:14:37

+0

谢谢Firoze!即使这可以在URLWithString中找到,但在那里看到它会更好。 – Zephyer 2013-02-25 13:19:22

回答

-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); 
}]; 
+0

在第一个和第二个位置的数据是相同的,并给出为 { “原产地”:“10.44.119.100” } – Zephyer 2013-02-25 14:03:31

+0

@Zephyer我编辑答案...请实施这种方式,看看你是否得到任何响应。 – yunas 2013-02-25 14:11:57

1

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

作为元注释:当问一个关于堆栈溢出的问题时,具体问题很重要。如果您发布了您在控制台中看到的错误,那么确定问题会更容易。同样,近似代码不是实际代码;如果您遇到问题,请详细说明发生了什么。细节很重要。