【问题标题】:How to use JMSSerializer with symfony 4.2如何在 symfony 4.2 中使用 JMSSerializer
【发布时间】:2019-09-06 11:56:30
【问题描述】:

我正在使用 symfony 4.2 构建一个 Api,并希望在使用 jms-serializer 安装后以 Json 格式序列化我的数据

composer 需要 jms/serializer-bundle

当我尝试以这种方式使用它时:

``` demands = $demandRepo->findAll();
    return $this->container->get('serializer')->serialize($demands,'json');```

它给了我这个错误:

Service "serializer" not found, the container inside "App\Controller\DemandController" is a smaller service locator that only knows about the "doctrine", "http_kernel", "parameter_bag", "request_stack", "router" and "session" services. Try using dependency injection instead.

【问题讨论】:

  • 离题。为什么要使用 JMSSerializer 而不是 Symfony 的默认序列化程序?顺便说一句,执行 php /bin/console debug:container 并检查服务是否存在。对于其他部分,最佳实践是由构造函数注入序列化程序。
  • 不使用 Symfony 序列化程序的原因是:它让我厌倦了对象的依赖关系 :'(。我现在就试试。

标签: symfony jmsserializerbundle jsonresponse symfony-4.2


【解决方案1】:

最后我使用 Symfony 序列化程序找到了答案 这很容易:

  • 首先:使用命令安装 symfony 序列化器:

composer 需要 symfony/序列化器

  • 第二个:使用serializerInterface:

.....//

use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;

// .....

.... //

 /**
     * @Route("/demand", name="demand")
     */
    public function index(SerializerInterface $serializer)
    {
        $demands = $this->getDoctrine()
            ->getRepository(Demand::class)
            ->findAll();

        if($demands){
            return new JsonResponse(
                $serializer->serialize($demands, 'json'),
                200,
                [],
                true
            );
        }else{
            return '["message":"ooooops"]';
        }

    }
    
    //......
    

有了它,我没有发现任何依赖关系或 DateTime 或其他问题的问题 ;)

【讨论】:

    【解决方案2】:

    正如我在评论中所说,您可以使用 Symfony 的默认序列化程序并通过构造函数将其注入。

    //...
    
    use Symfony\Component\Serializer\SerializerInterface;
    
    //...
    
    class whatever 
    {
        private $serializer;
    
        public function __constructor(SerializerInterface $serialzer)
        {
            $this->serializer = $serializer;
        }
    
        public function exampleFunction()
        {
            //...
            $data = $this->serializer->serialize($demands, "json");
            //...
        }
    }
    

    【讨论】:

    • 这并没有回答关于 JMS 序列化程序的问题...
    【解决方案3】:

    假设您有一个名为Foo.php 的实体,它具有idnamedescription

    并且您只想返回id,而name 在使用特定API(例如foo/summary/)时,在另一种情况下需要返回description 以及foo/details

    这里的序列化器真的很有帮助。

    use JMS\Serializer\Annotation as Serializer;
    
    /*
    * @Serializer\ExclusionPolicy("all")
    */
    class Foo {
        /**
        * @Serializer\Groups({"summary", "details"})
        * @Serializer\Expose()
        */
        private $id;
    
        /**
        * @Serializer\Groups({"summary"})
        * @Serializer\Expose()
        */
        private $title;
    
        /**
        * @Serializer\Groups({"details"})
        * @Serializer\Expose()
        */
        private $description;
    
    }
    
    

    让我们使用序列化器来获取依赖于组的数据

    class FooController {
        public function summary(Foo $foo, SerializerInterface $serialzer)
        {
            $context = SerializationContext::create()->setGroups('summary');
            $data = $serialzer->serialize($foo, json, $context);
    
            return new JsonResponse($data);
        }
    
        public function details(Foo $foo, SerializerInterface $serialzer)
        {
            $context = SerializationContext::create()->setGroups('details');
            $data = $serialzer->serialize($foo, json, $context);
    
            return new JsonResponse($data);
        }
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-11
      • 2019-11-13
      • 2011-12-08
      • 2019-09-07
      • 1970-01-01
      • 1970-01-01
      • 2019-05-20
      • 1970-01-01
      相关资源
      最近更新 更多