2015-07-19 170 views
1

我想通過json格式向服務器端的php文件發送數據數組(字典端),以便稍後將數據存儲到MySQL數據庫。但是,它看起來像由PHP接收的數據對象始終爲空。發送json數據到php返回null

下面是Objective-C的線:

NSURL *url = [NSURL URLWithString:@"http://myaddress/upload.php"]; 
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
[request setHTTPMethod:@"POST"]; 
[request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; 
[request setHTTPBody:self.sentData]; 

NSError *error = nil; 
NSURLResponse *response = nil; 
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 

if (error) NSLog(@"%s: NSURLConnection error: %@", __FUNCTION__, error);   
NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; 
NSLog(@"responseString: %@",responseString); 

下面是PHP行:

<?php 

$json_data=file_get_contents('php://input'); 
$post_data = json_decode($json_data); 

if (is_array($post_data)) 
$response = array("status" => "ok", "code" => 0, "original request" => $post_data); 
else 
$response = array("status" => "error", "code" => -1, "original_request" => $post_data); 

$processed = json_encode($response); 
echo $processed; 

?> 

上xcode中調試消息是如下:

2015-07-19 17:34:35.900 PhpPostTest[1531:557248] responseString: {"status":"error","code":-1,"original_request":null} 

貌似連接沒問題,但響應字符串表明php端收到的數據爲空。任何人都可以提出什麼是潛在的問題嗎?

+1

我可以看到您嘗試解碼的JSON嗎? – Hedam

+0

Jep,如果您試圖解析的json無效,json_decode返回null。所以$ json_data可能包含無效的json ...您嘗試解析它,$ post_data變爲null。 – Verkade89

回答

2

json_decode()將返回NULL只要您嘗試解碼的JSON格式錯誤。您可以運行echo $json_data;來驗證您的JSON實際上是JSON。

1

默認情況下,json_decode不會將解碼後的字符串作爲數組返回。如果你想讓它返回一個數組,你必須通過設置函數的第二個參數爲true來指定它。

json_decode($json_data, true); 

否則在這種情況下,json_decode可能會返回一個stdClass對象。當然,is_array檢查將評估爲false。

還要確保傳遞給json_decode函數的數據編碼爲UTF-8。它代表一個有效的json字符串,否則你會得到null。