繁体   English   中英

Symfony 4:使用 jms 序列化程序的 MaxDepth 注释

[英]Symfony 4 : Use MaxDepth annotation of jms serializer

我从 angular 端向 symfony 发送了一个 get http 请求以获取命令详细信息,我有许多嵌套的 json 对象和循环引用,我正在尝试将 MaxDepth 设置为相关实体,并且正如 jms 的文档所说添加这一行

$serializer->serialize($command, 'json', SerializationContext::create()->enableMaxDepthChecks()); 创建序列化程序上下文并启用 maxDepth 属性

这是我的实体

<?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation\MaxDepth;

/**
 * @ORM\Entity(repositoryClass="App\Repository\CommandRepository")
 */
class Command
{
    /**
     * @ORM\Id()
     * @ORM\Column(type="string", length=255)
     */
    private $id;

    /**
     * @ORM\Column(type="float")
     */
    private $price;


    /**
     * @ORM\Column(type="text")
     */
    private $adresse;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="commands")
     * @ORM\JoinColumn(nullable=true, onDelete="CASCADE")
     */
    private $user;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\CommandLine", mappedBy="command")
     */
    private $commandLines;


    /**
     * @ORM\OneToMany(targetEntity="App\Entity\GiftCheck", mappedBy="command")
     * @MaxDepth(1)
     */
    private $giftChecks;

命令详情的方法

/**
     * Get Commands.
     * @Rest\Get("/CommandDetails/{id}")
     * @param Request $request
     * @return View
     */

    public function CommandDetails( Request $request,$id)
    {
      $entityManager = $this->getDoctrine()->getManager();
      $command = $this->getDoctrine()->getRepository(Command::class)->find($id);
      $command-> setUser($this->getUserDetails(   $command-> getUser() ) );

      $serializer->serialize($command, 'json', SerializationContext::create()->enableMaxDepthChecks());
      return $this->handleView($this->view($command));
    }

服务器给出 500 错误似乎很正常,因为不知道 $serializer 变量,因为它没有初始化,我没有找到如何从什么接口初始化这个变量! 请帮忙?

跟随链接

您使用的 JMSSerializerBundle 是一项服务,您可以直接在控制器方法中自动装配它:

public function CommandDetails(Request $request, SerializerInterface $serializer, $id)

但首先添加到 service.yaml 文件的下一行:

services:
JMS\Serializer\SerializerInterface: '@jms_serializer'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM