Symfony + JMSSerializer throw 500 - handleCircularReference











up vote
1
down vote

favorite
1












I'm trying to use the JMSSerializer with Symfony to build a simple json api.



So i have 2 simple Entities (1 User can have many Cars, each Car belongs to one User):



class Car
{
/**
* @ORMId()
* @ORMGeneratedValue()
* @ORMColumn(type="integer")
*/
private $id;

/**
* @ORMColumn(type="string", length=255)
*/
private $name;

/**
* @ORMManyToOne(targetEntity="AppEntityUser", inversedBy="cars")
* @ORMJoinColumn(nullable=false)
*/
private $user;
}

class User extends BaseUser
{
/**
* @ORMId
* @ORMColumn(type="integer")
* @ORMGeneratedValue(strategy="AUTO")
*/
protected $id;

/**
* @ORMOneToMany(targetEntity="AppEntityCar", mappedBy="user", orphanRemoval=true)
*/
private $cars;
}


Now i want to get all Cars with their User.



My Controller:



class CarController extends AbstractController
{
/**
* @param CarRepository $carRepository
*
* @Route("/", name="car_index", methods="GET")
*
* @return Response
*/
public function index(CarRepository $carRepository)
{
$cars = $carRepository->findAll();
$serializedEntity = $this->container->get('serializer')->serialize($cars, 'json');

return new Response($serializedEntity);
}
}


This will throw a 500 error:




A circular reference has been detected when serializing the object of
class "AppEntityCar" (configured limit: 1)




Ok, sounds clear. JMS is trying to get each car with the user, and go to the cars and user ....



So my question is: How to prevent this behaviour? I just want all cars with their user, and after this, the iteration should be stopped.










share|improve this question


























    up vote
    1
    down vote

    favorite
    1












    I'm trying to use the JMSSerializer with Symfony to build a simple json api.



    So i have 2 simple Entities (1 User can have many Cars, each Car belongs to one User):



    class Car
    {
    /**
    * @ORMId()
    * @ORMGeneratedValue()
    * @ORMColumn(type="integer")
    */
    private $id;

    /**
    * @ORMColumn(type="string", length=255)
    */
    private $name;

    /**
    * @ORMManyToOne(targetEntity="AppEntityUser", inversedBy="cars")
    * @ORMJoinColumn(nullable=false)
    */
    private $user;
    }

    class User extends BaseUser
    {
    /**
    * @ORMId
    * @ORMColumn(type="integer")
    * @ORMGeneratedValue(strategy="AUTO")
    */
    protected $id;

    /**
    * @ORMOneToMany(targetEntity="AppEntityCar", mappedBy="user", orphanRemoval=true)
    */
    private $cars;
    }


    Now i want to get all Cars with their User.



    My Controller:



    class CarController extends AbstractController
    {
    /**
    * @param CarRepository $carRepository
    *
    * @Route("/", name="car_index", methods="GET")
    *
    * @return Response
    */
    public function index(CarRepository $carRepository)
    {
    $cars = $carRepository->findAll();
    $serializedEntity = $this->container->get('serializer')->serialize($cars, 'json');

    return new Response($serializedEntity);
    }
    }


    This will throw a 500 error:




    A circular reference has been detected when serializing the object of
    class "AppEntityCar" (configured limit: 1)




    Ok, sounds clear. JMS is trying to get each car with the user, and go to the cars and user ....



    So my question is: How to prevent this behaviour? I just want all cars with their user, and after this, the iteration should be stopped.










    share|improve this question
























      up vote
      1
      down vote

      favorite
      1









      up vote
      1
      down vote

      favorite
      1






      1





      I'm trying to use the JMSSerializer with Symfony to build a simple json api.



      So i have 2 simple Entities (1 User can have many Cars, each Car belongs to one User):



      class Car
      {
      /**
      * @ORMId()
      * @ORMGeneratedValue()
      * @ORMColumn(type="integer")
      */
      private $id;

      /**
      * @ORMColumn(type="string", length=255)
      */
      private $name;

      /**
      * @ORMManyToOne(targetEntity="AppEntityUser", inversedBy="cars")
      * @ORMJoinColumn(nullable=false)
      */
      private $user;
      }

      class User extends BaseUser
      {
      /**
      * @ORMId
      * @ORMColumn(type="integer")
      * @ORMGeneratedValue(strategy="AUTO")
      */
      protected $id;

      /**
      * @ORMOneToMany(targetEntity="AppEntityCar", mappedBy="user", orphanRemoval=true)
      */
      private $cars;
      }


      Now i want to get all Cars with their User.



      My Controller:



      class CarController extends AbstractController
      {
      /**
      * @param CarRepository $carRepository
      *
      * @Route("/", name="car_index", methods="GET")
      *
      * @return Response
      */
      public function index(CarRepository $carRepository)
      {
      $cars = $carRepository->findAll();
      $serializedEntity = $this->container->get('serializer')->serialize($cars, 'json');

      return new Response($serializedEntity);
      }
      }


      This will throw a 500 error:




      A circular reference has been detected when serializing the object of
      class "AppEntityCar" (configured limit: 1)




      Ok, sounds clear. JMS is trying to get each car with the user, and go to the cars and user ....



      So my question is: How to prevent this behaviour? I just want all cars with their user, and after this, the iteration should be stopped.










      share|improve this question













      I'm trying to use the JMSSerializer with Symfony to build a simple json api.



      So i have 2 simple Entities (1 User can have many Cars, each Car belongs to one User):



      class Car
      {
      /**
      * @ORMId()
      * @ORMGeneratedValue()
      * @ORMColumn(type="integer")
      */
      private $id;

      /**
      * @ORMColumn(type="string", length=255)
      */
      private $name;

      /**
      * @ORMManyToOne(targetEntity="AppEntityUser", inversedBy="cars")
      * @ORMJoinColumn(nullable=false)
      */
      private $user;
      }

      class User extends BaseUser
      {
      /**
      * @ORMId
      * @ORMColumn(type="integer")
      * @ORMGeneratedValue(strategy="AUTO")
      */
      protected $id;

      /**
      * @ORMOneToMany(targetEntity="AppEntityCar", mappedBy="user", orphanRemoval=true)
      */
      private $cars;
      }


      Now i want to get all Cars with their User.



      My Controller:



      class CarController extends AbstractController
      {
      /**
      * @param CarRepository $carRepository
      *
      * @Route("/", name="car_index", methods="GET")
      *
      * @return Response
      */
      public function index(CarRepository $carRepository)
      {
      $cars = $carRepository->findAll();
      $serializedEntity = $this->container->get('serializer')->serialize($cars, 'json');

      return new Response($serializedEntity);
      }
      }


      This will throw a 500 error:




      A circular reference has been detected when serializing the object of
      class "AppEntityCar" (configured limit: 1)




      Ok, sounds clear. JMS is trying to get each car with the user, and go to the cars and user ....



      So my question is: How to prevent this behaviour? I just want all cars with their user, and after this, the iteration should be stopped.







      symfony symfony4 jmsserializerbundle jms-serializer






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 8 at 10:16









      rob

      1,28351526




      1,28351526
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          2
          down vote



          accepted










          You need to add max depth checks to prevent circular references.
          This can be found in the documentation here



          Basically you add the @MaxDepth(1) annotation or configure max_depth if you're using XML/YML configuration. Then serialize like this:



          use JMSSerializerSerializationContext;

          $serializer->serialize(
          $data,
          'json',
          SerializationContext::create()->enableMaxDepthChecks()
          );


          Example Car class with MaxDepth annotation:



          class Car
          {
          /**
          * @JMSSerializerAnnotationMaxDepth(1)
          *
          * [..]
          */
          private $user;





          share|improve this answer























          • oh great. i didn't found this. thank you
            – rob
            Nov 8 at 12:24











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














           

          draft saved


          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53205621%2fsymfony-jmsserializer-throw-500-handlecircularreference%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          2
          down vote



          accepted










          You need to add max depth checks to prevent circular references.
          This can be found in the documentation here



          Basically you add the @MaxDepth(1) annotation or configure max_depth if you're using XML/YML configuration. Then serialize like this:



          use JMSSerializerSerializationContext;

          $serializer->serialize(
          $data,
          'json',
          SerializationContext::create()->enableMaxDepthChecks()
          );


          Example Car class with MaxDepth annotation:



          class Car
          {
          /**
          * @JMSSerializerAnnotationMaxDepth(1)
          *
          * [..]
          */
          private $user;





          share|improve this answer























          • oh great. i didn't found this. thank you
            – rob
            Nov 8 at 12:24















          up vote
          2
          down vote



          accepted










          You need to add max depth checks to prevent circular references.
          This can be found in the documentation here



          Basically you add the @MaxDepth(1) annotation or configure max_depth if you're using XML/YML configuration. Then serialize like this:



          use JMSSerializerSerializationContext;

          $serializer->serialize(
          $data,
          'json',
          SerializationContext::create()->enableMaxDepthChecks()
          );


          Example Car class with MaxDepth annotation:



          class Car
          {
          /**
          * @JMSSerializerAnnotationMaxDepth(1)
          *
          * [..]
          */
          private $user;





          share|improve this answer























          • oh great. i didn't found this. thank you
            – rob
            Nov 8 at 12:24













          up vote
          2
          down vote



          accepted







          up vote
          2
          down vote



          accepted






          You need to add max depth checks to prevent circular references.
          This can be found in the documentation here



          Basically you add the @MaxDepth(1) annotation or configure max_depth if you're using XML/YML configuration. Then serialize like this:



          use JMSSerializerSerializationContext;

          $serializer->serialize(
          $data,
          'json',
          SerializationContext::create()->enableMaxDepthChecks()
          );


          Example Car class with MaxDepth annotation:



          class Car
          {
          /**
          * @JMSSerializerAnnotationMaxDepth(1)
          *
          * [..]
          */
          private $user;





          share|improve this answer














          You need to add max depth checks to prevent circular references.
          This can be found in the documentation here



          Basically you add the @MaxDepth(1) annotation or configure max_depth if you're using XML/YML configuration. Then serialize like this:



          use JMSSerializerSerializationContext;

          $serializer->serialize(
          $data,
          'json',
          SerializationContext::create()->enableMaxDepthChecks()
          );


          Example Car class with MaxDepth annotation:



          class Car
          {
          /**
          * @JMSSerializerAnnotationMaxDepth(1)
          *
          * [..]
          */
          private $user;






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 8 at 10:28

























          answered Nov 8 at 10:20









          nifr

          39.4k7104114




          39.4k7104114












          • oh great. i didn't found this. thank you
            – rob
            Nov 8 at 12:24


















          • oh great. i didn't found this. thank you
            – rob
            Nov 8 at 12:24
















          oh great. i didn't found this. thank you
          – rob
          Nov 8 at 12:24




          oh great. i didn't found this. thank you
          – rob
          Nov 8 at 12:24


















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53205621%2fsymfony-jmsserializer-throw-500-handlecircularreference%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Schultheiß

          Liste der Kulturdenkmale in Wilsdruff

          Android Play Services Check