1

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

作曲家需要 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.

4

3 回答 3

1

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

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

作曲家需要 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 或其他问题的问题;)

于 2019-04-25T13:43:06.063 回答
0

正如我在评论中所说,您可以使用 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");
        //...
    }
}
于 2019-04-16T12:50:31.040 回答
0

假设您有一个名为Foo.phphas的实体idname并且description

并且您只想返回id,并且name在使用特定 API 时(例如在另一种情况下)也foo/summary/需要返回descriptionfoo/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);
    }
}

于 2019-04-16T13:15:23.607 回答