简体   繁体   中英

Symfony 4 : Use MaxDepth annotation of jms serializer

I send a get http request from angular side to symfony to get command details, I have many nested json objects and Circular Reference, I'm trying to set MaxDepth to the related entity and as the documentation of jms said add this line

$serializer->serialize($command, 'json', SerializationContext::create()->enableMaxDepthChecks()); to create a serializer context and enable the maxDepth property

This my entity

<?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;

Method of command details

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

it seems normal that the server give a 500 error cause didn't know the $serializer variable cause it's not initialized, I didn't found how to initialize this variable form what interface ! some help please ?

followed link

JMSSerializerBundle that you use it's a service and you can autowire it in your controller method directly:

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

But firstly add to service.yaml file next lines:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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