Giancarlo Ventura Granados Giancarlo Ventura Granados - 2 months ago 7
JSON Question

Return a JSON array from a Controller in Symfony

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.

I try the next code:

/**
* @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;
}


But I get
[{},{}]
as Response in the browser. I try with
$response = new Response(json_encode($categorias));
too, but I get the same result.

Answer

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;
}

It works perfect with any Query that Doctrine returns as array.

Comments