从Symfony中的Controller返回一个JSON数组

Gia*_*dos 11 php json symfony

我正在尝试从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;
    }
Run Code Online (Sandbox Code Playgroud)

但我[{},{}]在浏览器中得到了响应.我也尝试$response = new Response(json_encode($categorias));过,但是得到了相同的结果.

cha*_*asr 17

我认为@darkangelo的答案需要解释.

findAll()方法返回一组对象.

$categorias = $this->getDoctrine()
                   ->getRepository('AppBundle:Categoria')
                   ->findAll();
Run Code Online (Sandbox Code Playgroud)

要构建您的响应,您必须将实体的所有getter添加到您的响应中,例如:

$arrayCollection = array();

foreach($categorias as $item) {
     $arrayCollection[] = array(
         'id' => $item->getId(),
         // ... Same for each property you want
     );
}

return new JsonResponse($arrayCollection);
Run Code Online (Sandbox Code Playgroud)

使用QueryBuilder允许您将结果作为包含所有属性的数组返回:

$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
    'SELECT c
    FROM AppBundle:Categoria c'
);
$categorias = $query->getArrayResult();

return new JsonResponse($categorias);
Run Code Online (Sandbox Code Playgroud)

getArrayResult()避免了需要干将.


dar*_*elo 16

你需要这样做(根据以前的答案):

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;
}
Run Code Online (Sandbox Code Playgroud)

它适用于Doctrine作为数组返回的任何Query.

  • 您可以使用`JsonResponse`而不是`Response`来改善您的答案.这将避免重复使用`json_encode`和自定义标头. (12认同)

小智 6

/**
 * @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);
}
Run Code Online (Sandbox Code Playgroud)