2013-02-25 100 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

作爲元註釋:當問一個關於堆棧溢出的問題時,具體問題很重要。如果您發佈了您在控制檯中看到的錯誤,那麼確定問題會更容易。同樣,近似代碼不是實際代碼;如果您遇到問題,請詳細說明發生了什麼。細節很重要。