如何在 Symfony2 上将存储库对象作为 Json 返回 [英] How to return Repository Objects as Json on Symfony2
本文介绍了如何在 Symfony2 上将存储库对象作为 Json 返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试像这样返回用户,但当然它不起作用,因为我使用 BackboneJs,所以我需要数据作为 JSon
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));
}
推荐答案
感谢各位的帮助,这里是解决方案获取 JMSSerializerBundle,
Thanks for your help guys, here is the Solution Get the JMSSerializerBundle,
这是控制器上的代码
/**
* @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);
}
这篇关于如何在 Symfony2 上将存储库对象作为 Json 返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文