Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert object to JSON in symfony2

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

like image 516
Mirage Avatar asked Aug 08 '12 05:08

Mirage


1 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'));
like image 108
Inoryy Avatar answered Oct 14 '22 09:10

Inoryy