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 !

3
  • You can possibly convert your object into an array before sending it as a response. See here Commented Dec 2, 2015 at 18:59
  • I already tried to cast $datas = (array)$datas. But it doesn't work Commented Dec 3, 2015 at 15:44
  • Such problem also may be relevant with stackoverflow.com/questions/55104868/… Commented Jul 3, 2019 at 12:30

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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.
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. 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?
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 ?
Yes, it will. In order to get an array out of json_encode you must have an array with no indices as an input.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.