Mirage
Mirage

Reputation: 31548

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

Upvotes: 8

Views: 14239

Answers (2)

ludriv
ludriv

Reputation: 291

Try {{ your_variable|raw }}

Sorry for late

Upvotes: 0

Inoryy
Inoryy

Reputation: 8425

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

Upvotes: 6

Related Questions