2015-01-25 16 views
9

Sto cercando di restituire una risposta JSON da un controller in Symfony 2. Esempio di modulo, in Spring MVC È possibile ottenere una risposta JSON con annotazione @ResponseBody. Voglio ottenere una risposta JSON, nessun MTT se si tratta di un JSON Array o di un oggetto Json, quindi manipolarlo con javascript nella vista.Restituisce un array JSON da un controller in Symfony

cerco il codice successivo:

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

ma ho [{},{}] come risposta nel browser. Provo anche con $response = new Response(json_encode($categorias));, ma ottengo lo stesso risultato.

+0

Hai provato a "restituire nuovo JSONResponse ($ dati);"? – Neal

risposta

7

Hai bisogno di fare questo (in base alla risposta precedente):

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

Funziona perfettamente con qualsiasi query che restituisce dottrina come array.

+8

Puoi migliorare la tua risposta usando 'JsonResponse' invece di' Response'. Ciò eviterà usi duplicati di 'json_encode' e intestazioni personalizzate. – chalasr

1

è necessario modificare il codice in questo modo:

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

Se il servizio serializer non è abilitato, è necessario abilitarlo in app/config/config.yml:

framework: 
     # ... 
     serializer: 
      enabled: true 

Per le opzioni più avanzate per la serializzazione, è possibile installare JMSSerializerBundle

+0

Viene visualizzato un errore 500: è stato richiesto un "serializzatore" di servizio inesistente. –

+0

È necessario abilitare prima il servizio serializzatore. In app/config/config.yml aggiungere questo: 'quadro: # ...Serializzatore : abilitato: true' –

+0

Ottengo la soluzione: $ categorias = $ query-> getArrayResult(); \t \t // $ response-> intestazioni-> set ('Content-Type', 'application/json'); \t \t // return $ response; \t \t // return $ this-> render ('AppBundle: Front: test.html.twig', array ('otra' => $ otra)); \t \t return new Response (json_encode ($ categorie), 200); –

0

Suggerisco la seguente soluzione:

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

Probabilmente dovresti usare newJsonResponse come hai fatto nella tua domanda. – Cerad

11

Penso che la risposta di @darkangelo abbia bisogno di spiegazioni.

Il metodo findAll() restituire un insieme di oggetti.

$categorias = $this->getDoctrine() 
        ->getRepository('AppBundle:Categoria') 
        ->findAll(); 

Per costruire la vostra risposta, bisogna aggiungere tutti i getter delle vostre entità per la vostra risposta come:

$arrayCollection = array(); 

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

return new JsonResponse($arrayCollection); 

Usa QueryBuilder consente di restituire i risultati come array che contiene tutte le proprietà:

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

return new JsonResponse($categorias); 

Il getArrayResult() evita bisogno di getter.

Problemi correlati