简体   繁体   中英

Symfony ObjectNormalizer empty property path

I'm currently trying to serialize a pretty complex object to return it as a response in json with the Symfony Serializer. I got the following object:

/**
* @Doctrine\Entity
* @Doctrine\Table(name="Fichiers")
*/
class Fichier{

/**
* @Doctrine\Column(name="id", type="integer")
* @Doctrine\Id
* @Doctrine\GeneratedValue(strategy="AUTO")
*/
protected $id;

/**
* @Doctrine\OneToOne(targetEntity="Utilisateur")
* @Doctrine\JoinColumn(name="idProprietaire", referencedColumnName="id", nullable=true)
*/
protected $proprietaire;

/**
* @Doctrine\OneToOne(targetEntity="Fichier")
* @Doctrine\JoinColumn(name="idParent", referencedColumnName="id")
*/
protected $parent;

/**
* @Doctrine\Column(name="estDossier", type="boolean")
* @Assert\NotBlank()
*/
protected $estDossier;

/**
* @Doctrine\Column(name="nom", type="string", length=250)
* @Assert\NotBlank()
*/
protected $nom;

/**
* @Doctrine\ManyToMany(targetEntity="Groupe")
* @Doctrine\JoinTable(name="Fichiers_Groupes",
*      joinColumns={@Doctrine\JoinColumn(name="idFichier", referencedColumnName="id")},
*      inverseJoinColumns={@Doctrine\JoinColumn(name="idGroupe", referencedColumnName="id")}
* )
*/
protected $groupes;

/**
* @Doctrine\Column(name="extension", type="string", length=10)
*/
protected $extension;

/**
* @Doctrine\Column(name="dateCreation", type="datetime")
*/
protected $dateCreation;

/**
* @Doctrine\Column(name="dateModification", type="datetime")
*/
protected $dateModification;

/**
* @Doctrine\Column(name="taille", type="integer")
*/
protected $taille;

And here's my controller code:

$fichier = $this->getDoctrine()->getRepository(Fichier::class)->find($idFichier);
$encoder = new JsonEncoder();
$normalizer = new ObjectNormalizer();
$normalizer->setCircularReferenceHandler(function ($object) {
    return $object->getId();
});
$serializer = new Serializer(array($normalizer), array($encoder));
$jsonContent = $serializer->serialize($fichier, 'json');

I get the following error:

The property path should not be empty.

After some testing, I found out that if I manually set the null properties of my object, I wouldn't get this error, but another one where it fails at converting it in string. After making this function:

public function __toString()
{
    return strval( $this->getId() );
}

I get this error, considering id = 4:

Notice: Undefined variable: 4

Is there any way so that the normalizer handles the null properties and/or to fix this error?

It is not easy to help because I haven't the mapping of the related entities and the serializer handle the nested properties of objects. The serializer haven't any problems with the null values. Please give us more context of your error, like stacktrace

By the way I have an advice for you to avoid pollute your controller. You should create a custom Serializer. Doing this symfony will automatically call this class to serialize your Fichier entity and you can add custom logic in

class FichierSerializer implements NormalizerInterface
{
    function __construct()
    {
        $encoder = new JsonEncoder();
        $normalizer = new ObjectNormalizer();
        $normalizer->setCircularReferenceHandler(function ($object) {
            return $object->getId();
        });
        $this->setSerializer(new Serializer(array($normalizer), array($encoder)));
    }

    public function normalize($object, $format = null, array $context = [])
    {
           /** @var Fichier $object */

           return [
               'nom' => $object->getNom()
               // Your data to return as json
           ];
    }

    public function supportsNormalization($data, $format = null)
    {
        return $data instanceof Fichier;
    }
}

 // In your FichierController.php ? 
 public function getFichierAction($idFichier) {
      $fichier = $this->getDoctrine()->getRepository(Fichier::class)->find($idFichier);
      return Response::create($this->get('serializer')->serialize($fichier, 'json'));
}

And then add this to your services.yml file

app.serializer.fichier:
    class: ApiBundle\Serializer\FichierSerializer
    tags:
        - { name: serializer.normalizer }

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