从Symfony中的Controller返回JSON数组 [英] Return a JSON array from a Controller in Symfony
问题描述
我正在尝试从Symfony 2中的控制器返回JSON响应.在Spring MVC的示例中,我可以使用@ResponseBody注释获得JSON响应.我想得到一个JSON响应,如果它是JSON数组或Json对象,则不作任何处理,然后在视图中使用javascript对其进行处理.
I am trying return a JSON response from a controller in Symfony 2. Form example, in Spring MVC I can get a JSON response with @ResponseBody annotattion. I want get a JSON response, no mtter if it is a JSON Array or a Json Object, then, manipulate it with javascript in the view.
我尝试下一个代码:
/**
* @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));
,但得到的结果相同.
But I get [{},{}]
as Response in the browser. I try with $response = new Response(json_encode($categorias));
too, but I get the same result.
推荐答案
您需要执行此操作(基于先前的答案):
You need to do this (based on previous answer):
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以数组形式返回的任何查询完美配合.
It works perfect with any Query that Doctrine returns as array.
这篇关于从Symfony中的Controller返回JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!