How to return Repository Objects as Json on Symfon

2020-07-29 23:33发布

I'm trying to return the users like this, but of course it doesn't work, I need the data as JSon since im working with BackboneJs

/**
* @Route("/mytest",name="ajax_user_path")
*/
public function ajaxAction()
{
    $em = $this->get('doctrine')->getManager();
    $users = $this->get('doctrine')->getRepository('GabrielUserBundle:Fosuser')->findAll();

    $response = array("users"=>$users);            
    return new Response(json_encode($response));
}

标签: json symfony
4条回答
够拽才男人
2楼-- · 2020-07-30 00:12

So, findAll returns an array of entities (objects) and json_encode cannot correctly encode that array. You have to prepare your data berofe send response like that:

Example:

use Symfony\Component\HttpFoundation\JsonResponse;

/**
* @Route("/mytest",name="ajax_user_path")
*/
public function ajaxAction()
{
    $users = $this->get('doctrine')->getRepository('GabrielUserBundle:Fosuser')->findAll();
    $response = array();
    foreach ($users as $user) {
        $response[] = array(
            'user_id' => $user->getId(),
            // other fields
        );
    }

    return new JsonResponse(json_encode($response));
}

Moreover, it would be great if you put preparing response to ex. UserRepository class.

查看更多
混吃等死
3楼-- · 2020-07-30 00:15

I have never tried to encode a complete object, but I have used json with arrays of informations like this:

$vars = array( 
   'test' => 'test'
);            
$response = new JsonResponse($vars);

return $response;

As you can see in JsonResponse, its function setData() is encoding the array, so you don't have to do it yourself:

public function setData($data = array())
{
    // Encode <, >, ', &, and " for RFC4627-compliant JSON, which may also be embedded into HTML.
    $this->data = json_encode($data, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);

    return $this->update();
}
查看更多
唯我独甜
4楼-- · 2020-07-30 00:16

With Symfony you have JsonResponse like :

return new JsonResponse($users);

And don't forget to add the header :

use Symfony\Component\HttpFoundation\JsonResponse;
查看更多
Animai°情兽
5楼-- · 2020-07-30 00:21

Thanks for your help guys, here is the Solution Get the JMSSerializerBundle,

This is the code on the controller

/**
     * @Route("/user")
     * @Template()
     */
    public function userAction()
    {
        $em = $this->get('doctrine')->getManager();
        $users = $this->get('doctrine')->getRepository('GabrielUserBundle:Fosuser')->findAll();

        $serializer = $this->get('jms_serializer');
        $response = $serializer->serialize($users,'json');

        return new Response($response);
    }
查看更多
登录 后发表回答