簡體   English   中英

使用 jms_serializer 將實體轉換為 json 的問題 - Symfony 4

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

我正在嘗試制作一個 api 以使用 symfony 4 返回一個 json 我創建了一個實體並且它工作正常但它不會將數據庫的數據轉換為 json 所以來自“Symfony\\Component\\Serializer\\Serializer”的序列化程序給我錯誤

 serialization for the format json is not supported

所以我嘗試了 Jms_Serializer 但在官方網站上他們使用舊版本的 symfony 我安裝了捆綁包

composer require jms/serializer-bundle   

這是控制器中的代碼

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

        }
    }

我收到此錯誤: 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

一個簡單的 json_encode() 結果給我一個空的 json

沒關系,它工作正常問題出在 AbstractController 類上,我將其更改為 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);

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM