Lorsque vous essayez de faire une fonction qui sérialise un objet, le transformer en un JSON et l'envoyer comme réponse http je reçois l'erreur suivante:serialize symfony et Normaliser rendant JSON incompatible
ContextErrorException
Runtime Notice: Declaration of AppBundle\Controller\DefaultController::json() should be compatible with Symfony\Bundle\FrameworkBundle\Controller\Controller::json($data, $status = 200, $headers = Array, $context = Array)
j'ai pu afficher un tableau d'utilisateurs via var_dump(); avant d'essayer de sérialiser l'objet et de l'utiliser dans une fonction. Voici mon code:
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
class DefaultController extends Controller
{
public function indexAction(Request $request)
{
// replace this example code with whatever you need
return $this->render('default/index.html.twig', [
'base_dir' =>realpath($this->getParameter('kernel.project_dir')).DIRECTORY_SEPARATOR,
]);
}
public function pruebasAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$users = $em->getRepository('BackendBundle:User')->findAll();
return $this->json($users);
}
public function json($data){
$normalizers = array(new ObjectNormalizer());
$encoders = array(new JsonEncoder());
$serializer = new Serializer($normalizers, $encoders);
$json = $serializer->serialize($data, 'json');
$response = new Response($json);
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
Qu'est-ce que la "fonction publique JSON ($ data) {}" faire pour être déconner avec le programme?
et comment rendre mon json compatible avec celui du framework?
P.D .: Soyez patient. Je suis nouveau avec le cadre
double possible de [Déclaration de Les méthodes devraient être compatibles avec les méthodes parent en PHP] (https://stackoverflow.com/questions/3115388/declaration-of-methods-should-be-compatible-with-parent-methods-in-php) – iainn
Comme vous avez un typo, 'appplication/json' devrait être' application/json' –