jsonsymfonyentitysymfony4jms-serializer

problem with converting a entity to json using jms_serializer - Symfony 4


i'm trying to make an api to return a json with symfony 4 i create a entity and it's work fine but it do not convert data for database to json so the Serializer from "Symfony\Component\Serializer\Serializer" give me error

 serialization for the format json is not supported

so i tried the Jms_Serializer but in the official website they work with a old version of symfony i installed the bundle with

composer require jms/serializer-bundle   

this the code in controller

class ProduitsController extends AbstractController
    {
        /**
         * @Route("/api/produits/cuisine")
         */
        public function index()
        {
            $dc = $this->getDoctrine();

            $Produits=$dc->getRepository(Article::class)->findAll();

            $data= $this->get('jms_serializer')->serialize($Produits,'json');

            return new JsonResponse($data);

        }
    }

i got this error : ServiceNotFoundException

Service "jms_serializer" not found: even though it exists in the app's 
container, the container inside "App\Controller\ProduitsController" is a
 smaller service locator that only knows about the "doctrine", "form.factory",
 "http_kernel", "parameter_bag", "request_stack", "router", 
"security.authorization_checker", "security.csrf.token_manager", 
"security.token_storage", "serializer", "session" and "twig" services. Try
 using dependency injection instead

a simple json_encode() to the result give me a empty json


Solution

  • It's ok it work fine the problem was with the class AbstractController i change it to Controller

    class ProduitsController extends Controller
    {
        /**
         * @Route("/api/produits/cuisine")
         */
        public function index()
        {
            $dc = $this->getDoctrine();
            $Produits=$dc->getRepository(Article::class)->findAll();
            $data= $this->get('jms_serializer')->serialize($Produits,'json');
    
            return new JsonResponse($data);
    
        }
    }