2017-04-25 133 views
0

我有Json::decode問題。我正在使用此代碼:Json :: decode返回NULL

use Drupal\Component\Serialization\Json; 

$client = \Drupal::httpClient(); 
$request = $client->post($rest_url, [ 
     'form_params' => [ 
      'id' => $rest_id, 
     ], 
     ]); 
     $response = Json::decode($request->getBody()); 

從某個服務器獲取JSON,但它返回NULL。當然,這僅僅是一個部分的代碼(不trycatch ...)

$request->getBody()回報是好的,但在Json::decode我仍然得到NULL。我注意到的唯一的事情是在Postman中,當我看着原始的內容時,我在JSON的開頭看到了一些空行(如鍵入時鍵盤上的返回鍵),但是我檢查了JSON,因爲它處於打開狀態JSONLint它是有效的。

任何想法是什麼問題?

+1

看起來像Json :: decode只會調用PHP的本機'json_dcode' ...所以使用'json_last_error' /'json_last_error_msg'來找出錯誤。 – CBroe

+0

是的,它的語法錯誤...所以我會從客戶端請求固定的JSON(因爲它是通過一些他們的內部軟件生成的)...謝謝... – mixerowsky

回答

0

我不熟悉Drupal的JSON序列化程序,但嘗試強制響應身體對話到一個字符串。

$response = Json::decode($request->getBody()->getContents()); 

狂飲從getBody()返回Stream對象,也可能是這個問題。