How to convert object to JSON in symfony2

Mirage picture Mirage · Aug 8, 2012 · Viewed 13.7k times · Source

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

Answer

Inoryy picture Inoryy · Aug 8, 2012

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'));