douyu4535 2017-07-20 19:20
浏览 33

Symfony ObjectNormalizer空属性路径

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?

  • 写回答

1条回答 默认 最新

  • dsfdsf21312 2017-07-21 15:06
    关注

    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 }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀