-2
當試圖使該序列化對象的功能,把它變成一個JSON並把它作爲一個HTTP響應我得到以下錯誤:symfony的序列化和標準化使得JSON不相容
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)
我能通過var_dump()顯示用戶數組;在我試圖序列化對象並在函數中使用它之前。這是我的代碼:
<?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;
}
}
「public function json($ data){}」做了什麼來搞亂程序?
以及如何讓我的JSON與框架中的JSON兼容?
P.D .:要有耐心。我是新與框架
的[聲明可能重複方法應該與PHP中的父方法兼容](https://stackoverflow.com/questions/3115388/declaration-of-methods-should-be-compatible-with-parent-methods-in-php) – iainn
順便說一句,你有一個錯字,'appplication/json'應該是'application/json' –