简体   繁体   中英

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

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

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM