Home » Php » php – How to convert object to JSON in symfony2

php – How to convert object to JSON in symfony2

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am using this:

    $users = $em->getRepository('UserBundle:User')->getallUsers($search);
    $response = new Response(json_encode($users));
    $response->headers->set('Content-Type', 'application/json');
    return $response;

Users are multiple entities not single result.

But I am getting this:

[{},{},{},{},{},{}]

I want something like:

[ { label: $user.getName(), value: $user.getId() }, ... ]

How can i do that?

EDIT: I also tried json_encode($users->toArray()) then I get this error:

Call to a member function toArray() on a non-object

How to&Answers:

You need to have a way to serialize your objects, you can’t expect json_encode to magically guess which fields are allowed to be encoded.

A good bundle I recommend for this task is JMSSerializerBundle.
Make sure you read through documentation carefully before using it!

End result will probably look like this:

$users = $em->getRepository('UserBundle:User')->getallUsers($search);
$response = new Response($container->get('serializer')->serialize($users, 'json'));

Answer:

Try {{ your_variable|raw }}

Sorry for late