2中使用JMSSerializer

2中使用JMSSerializer

本文介绍了如何在Symfony 4.2中使用JMSSerializer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用symfony 4.2构建一个Api,并想在通过

i am building an Api with symfony 4.2 and want to use jms-serializer to serialize my data in Json format, after installing it with

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

and when i try to use it this way :

``` 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的默认序列化器,并使用它由构造函数注入.

As I said in my comment, you could use the default serializer of Symfony and use it injecting it by the constructor.

//...

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");
        //...
    }
}

这篇关于如何在Symfony 4.2中使用JMSSerializer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 19:10