从 Symfony 中的控制器返回 JSON 数组

2022-08-30 20:27:25

我正在尝试从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

我认为@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

您需要执行此操作(基于先前的答案):

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 作为数组返回的任何查询。


推荐