How to get an array instead of an object when requesting JSON data using HTTPful

I use HTTPful to send some requests to PHP and receive data in JSON, but the library converts the result to objects where I want the result to be an array. In other words, he performs json_decode($data), not json_decode($data, true).

There is, somewhere, an opportunity to use the latter, but I cannot understand where. An option has been added in v0.2.2:

- FEATURE Add support for parsing JSON responses as associative arrays instead of objects

But I read the documentation and even the source , and I don’t see the option anywhere ... The only way I can think of is to make my own MimeHandlerAdapter, which does a json_decode($data, true), but it seems like a pretty reverse way to do it if there is an option somewhere...

+4
source share
3 answers

It may be a bit late to answer this, but I did a little research using Httpful and found the answer. Httpful uses the default set of handlers for each mime type. If someone is registered before sending a request, he will use the one that you registered. Conveniently, there is a class Httpful\Handlers\JsonHandler. The constructor takes an array of arguments. The only one he uses is this $decode_as_array. Therefore, you can force it to return an array as follows:

// Create the handler
$json_handler = new Httpful\Handlers\JsonHandler(array('decode_as_array' => true));
// Register it with Httpful
Httpful\Httpful::register('application/json', $json_handler);
// Send the request
$response = Request::get('some-url')->send();

UPDATE

, funky-, , JSON. , , . , , , JSON :

$response = Request::get('some/awesome/url')
    ->expects('application/json')
    ->send();
+3

. , src/Httpful/Handlers/JsonHandler.php 11.

:

private $decode_as_array = false;

27:

$parsed = json_decode($body, $this->decode_as_array);
+2

decode_as_array true, :

\Httpful\Httpful::register(\Httpful\Mime::JSON, new \Httpful\Handlers\JsonHandler(array('decode_as_array' => true)));

::

0

All Articles