Php 从Symfony中的控制器返回JSON数组
我正在尝试从Symfony 2中的控制器返回JSON响应。例如,在SpringMVC中,我可以获得带有@ResponseBody注释设置的JSON响应。我想要得到一个JSON响应,如果它是JSON数组或JSON对象,则不需要mtter,然后在视图中使用javascript对其进行操作 我尝试下一个代码:Php 从Symfony中的控制器返回JSON数组,php,json,symfony,Php,Json,Symfony,我正在尝试从Symfony 2中的控制器返回JSON响应。例如,在SpringMVC中,我可以获得带有@ResponseBody注释设置的JSON响应。我想要得到一个JSON响应,如果它是JSON数组或JSON对象,则不需要mtter,然后在视图中使用javascript对其进行操作 我尝试下一个代码: /** * @Route( * "/drop/getCategory/", * name="getCategory" * )
/**
* @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=newresponse(json_encode($categorias))代码>也是,但我得到了相同的结果 您需要以这种方式更改代码:
/**
* @Route(
* "/drop/getCategory/",
* name="getCategory"
* )
* @Method("GET")
*/
public function getAllCategoryAction() {
$categorias = $this->getDoctrine()
->getRepository('AppBundle:Categoria')
->findAll();
$categorias = $this->get('serializer')->serialize($categorias, 'json');
$response = new Response($categorias);
$response->headers->set('Content-Type', 'application/json');
return $response;
}
如果未启用序列化程序
服务,则必须在app/config/config.yml
中启用它:
framework:
# ...
serializer:
enabled: true
有关更高级的序列化选项,您可以安装我建议使用以下解决方案:
/**
* @Route(
* "/drop/getCategory/",
* name="getCategory"
* )
* @Method("GET")
*/
public function getAllCategoryAction() {
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT c
FROM AppBundle:Categoria c'
);
$categorias = $query->getArrayResult();
return new Response(json_encode($categorias), 200);
}
看起来您正在尝试将集合放入响应中。为此,您需要设置序列化程序(或以数组形式检索数据)
查看此文档页面:
及
.您需要这样做(基于前面的答案):
它可以完美地处理作为数组返回的任何查询 我认为@darkangelo的答案需要解释
findAll()
方法返回对象的集合
$categorias = $this->getDoctrine()
->getRepository('AppBundle:Categoria')
->findAll();
$data = $serializer->serialize($cities, 'json');
要构建响应,必须将实体的所有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()
避免了对getter的需要。根据最佳实践,我成功地通过以下方式实现了这一点:
public function index(CityRepository $cityRepository,
SerializerInterface $serializer): Response
注入存储库和序列化程序
$cities = $cityRepository->findAll();
检索对象数组
$categorias = $this->getDoctrine()
->getRepository('AppBundle:Categoria')
->findAll();
$data = $serializer->serialize($cities, 'json');
将数据序列化为JSON字符串
return new JsonResponse($data, 200, [], true);
将JSON字符串传递到JsonResponse
时出现500错误:您请求了一个不存在的服务“serializer”。您必须首先启用serializer服务。在app/config/config.yml中添加以下内容:framework:#。。。序列化程序:enabled:true
我得到解决方案:$categorias=$query->getArrayResult();//$response->headers->set('Content-Type','application/json');//返回$response;//返回$this->render('AppBundle:Front:test.html.twig',数组('otra'=>$otra));返回新的响应(json_encode($categorias),200);这也是一个很好的解决方案。使用序列化程序服务不起作用?我发现使用序列化是一种更好的做法。您可能应该像在您的问题中那样使用newJsonResponse。您是否尝试过“返回新的JSONResponse($data);”?您可以使用JsonResponse
而不是Response
来改进答案。这将避免重复使用json\u encode
和自定义头。我得到一个非常难看的对象“{\u0022id\u0022:105\u0022name\u0022:\u00223…”如何修复它?@ArturO本例中的序列化程序返回一个json字符串;检查JsonResponse
是否将最后一个参数设置为true。
/**
* @Route("/api/list", name="list")
*/
public function getList(SerializerInterface $serializer, SomeRepository $repo): JsonResponse
{
$models = $repo->findAll();
$data = $serializer->serialize($models, JsonEncoder::FORMAT);
return new JsonResponse($data, Response::HTTP_OK, [], true);
}