作者:沙上的蜃楼 | 来源:互联网 | 2023-05-25 09:20
我正在尝试从Symfony 2中的控制器返回JSON响应.形式示例,在Spring MVC中,我可以使用@ResponseBody注释获得JSON响应.我想得到一个JSON响应,如果它是一个JSON数组或一个Json对象,则没有mtter,然后在视图中使用Javascript操作它.
我尝试下一个代码:
/**
* @Route(
* "/drop/getCategory/",
* name="getCategory"
* )
* @Method("GET")
*/
public function getAllCategoryAction() {
$categorias = $this->getDoctrine()
->getRepository('AppBundle:Categoria')
->findAll();
$respOnse= new JsonResponse();
$response->setData($categorias);
$response->headers->set('Content-Type', 'application/json');
return $response;
}
但我[{},{}]
在浏览器中得到了响应.我也尝试$respOnse= new Response(json_encode($categorias));
过,但是得到了相同的结果.
1> chalasr..:
我认为@darkangelo的答案需要解释.
该findAll()
方法返回一组对象.
$categorias = $this->getDoctrine()
->getRepository('AppBundle:Categoria')
->findAll();
要构建您的响应,您必须将实体的所有getter添加到您的响应中,例如:
$arrayCollection = array();
foreach($categorias as $item) {
$arrayCollection[] = array(
'id' => $item->getId(),
// ... Same for each property you want
);
}
return new JsonResponse($arrayCollection);
使用QueryBuilder
允许您将结果作为包含所有属性的数组返回:
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT c
FROM AppBundle:Categoria c'
);
$categorias = $query->getArrayResult();
return new JsonResponse($categorias);
在getArrayResult()
避免了需要干将.
2> darkangelo..:
你需要这样做(根据以前的答案):
public function getAllCategoryAction() {
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT c
FROM AppBundle:Categoria c'
);
$categorias = $query->getArrayResult();
$respOnse= new Response(json_encode($categorias));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
它适用于Doctrine作为数组返回的任何Query.
您可以使用`JsonResponse`而不是`Response`来改善您的答案.这将避免重复使用`json_encode`和自定义标头.