How get a valid JSON output from the response in Zend Framework 3?

家住魔仙堡 提交于 2019-12-11 04:46:31

问题


I'm writing a client for an API...

use Zend\Http\Client;
use Zend\Http\Request;
use Zend\Json\Json;
...
$request = new Request();
$request->getHeaders()->addHeaders([
    'Accept-Charset' => 'UTF-8',
    'Accept' => 'application/hal+json',
    'Content-Type' => 'application/hal+json; charset=UTF-8',
]);
$apiAddress = 'http://my.project.tld/categories';
$request->setUri($apiAddress);
$request->setMethod('GET');
$client = new Client();
$response = $client->dispatch($request);
$data = $response->getContent();

... and get a broken JSON like this:

1f9e <-- What is it?
{"_links...
\u043 <-- What is it?
1a6...
tfoli <-- What is it?
0

The string is separaten into five lines:

  • 1st line: only 1f9e
  • 2nd line: first content part
  • 3d line: string 1a6
  • 4th line: the second content part
  • 5th line: 0

Why am I getting additional symbols/strings? How to avoid this a get valid JSON output?


回答1:


The problem with the getContent() method of the response object. It may not decode the content it gets in it from the request. Please have a look at here. This might be the reason. I may be wrong!

So the getBody() method of it does the decoding job for the content of the request. So please use this method instead of getContent().

$data = $response->getBody();

Hope this would help you!



来源:https://stackoverflow.com/questions/44978260/how-get-a-valid-json-output-from-the-response-in-zend-framework-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!