如何在 symfony 4.2 中使用 JMSSerializer

How to use JMSSerializer with symfony 4.2

我正在使用 symfony 4.2 构建一个 Api 并希望在使用

安装后使用 jms-serializer 以 Json 格式序列化我的数据

composer require 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.

正如我在评论中所说,您可以使用 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");
        //...
    }
}

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

并且您只想 return id,而 name 在消耗特定 API 时 foo/summary/ 在另一种情况下需要 return 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);
    }
}

最后我使用 Symfony 序列化程序找到了答案 非常简单:

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

composer require symfony/serializer

  • 第二个:使用序列化接口:

.....//

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 或其他问题 ;)