1

There is my function :

private function responseJson($datas, $code)
{
    $serializer = $this->container->get('jms_serializer');
    $context = new SerializationContext();
    $context->setSerializeNull(true);
    $response = new Response($serializer->serialize($datas, 'json', $context->enableMaxDepthChecks()), $code);
    $response->headers->set('Content-Type', 'application/json');
    return $response;
}

I use serializer components of symfony. This is what my server do when I call this function. The client need an array but the server returns an object. Is it possible to force to return an array ?

Thanks for your answers !

Yoann Picquenot
  • 640
  • 10
  • 26
  • You can possibly convert your object into an array before sending it as a response. See [here](http://stackoverflow.com/questions/4345554/convert-php-object-to-associative-array) – Dipen Shah Dec 02 '15 at 18:59
  • I already tried to cast `$datas = (array)$datas`. But it doesn't work – Yoann Picquenot Dec 03 '15 at 15:44
  • Such problem also may be relevant with https://stackoverflow.com/questions/55104868/symfony-4-doctrine-2-serialize-after-removing-first-item-from-collection-cau/56867626#56867626 – Storm Jul 03 '19 at 12:30

1 Answers1

1

From what I read in the JsonSerializationVisitor the actual encoding is done with json_encode:

$result = @json_encode($this->getRoot(), $this->options);

As I can read in this post the forced creation of an array with json_encode cannot be done.

If your input data would be an array without indices, then json_encode would produce an array. That means that if key names in your data do matter, you cannot return an array to the client.

Community
  • 1
  • 1
Michał Tomczuk
  • 531
  • 3
  • 10
  • Okay, I consider again results given, and there are keys. So as you said, Client can't get an array. So I try an `array_values($datas)` to remove keys, but It doesn't work. – Yoann Picquenot Dec 03 '15 at 15:46
  • I've made a quick project in Symfony 2.7.7, installed jms/serializer-bundle and pasted your code into the controller. I've given that controller three different arrays treated with array_values. You can [see the code here](http://pastebin.com/jqvVXdUr). No matter which array I choose, I always get an array as a response. I cannot imagine that your `$datas` array can cause the response to be an object, but maybe you can show an example of how it looks like? – Michał Tomczuk Dec 03 '15 at 18:11
  • Thanks for you for what you did. And what happened if $datas is already an object and not an array ? It will return an object, will it ? – Yoann Picquenot Dec 06 '15 at 15:40
  • Yes, it will. In order to get an array out of `json_encode` you must have an array with no indices as an input. – Michał Tomczuk Dec 08 '15 at 08:09