How to convert an object to JSON in symfony2

I use 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 several objects that do not have a separate result.

But I get the following:

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

I need something like:

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

How can i do this?

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

Call toArray() member function for a non-object

+7
source share
2 answers

You should have a way to serialize your objects, you cannot expect json_encode magically guess which fields are allowed for encoding.

A good package that I recommend for this task is the JMSSerializerBundle . Read the documentation carefully before use.

The end result will probably look like this:

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

Try {{ your_variable|raw }}

Sorry lately

0
source

All Articles