简体   繁体   English

Symfony ObjectNormalizer空属性路径

[英]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. 我目前正在尝试序列化一个非常复杂的对象,以使用Symfony序列化程序将其作为json中的响应返回 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. 经过一些测试,我发现,如果手动设置对象的null属性,则不会收到此错误,但会收到另一个错误,无法将其转换为字符串。 After making this function: 完成此功能后:

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

I get this error, considering id = 4: 考虑到id = 4,我收到此错误:

Notice: Undefined variable: 4 注意:未定义变量:4

Is there any way so that the normalizer handles the null properties and/or to fix this error? 有什么方法可以使规范化器处理null属性和/或解决此错误?

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. 序列化程序对于null值没有任何问题。 Please give us more context of your error, like stacktrace 请给我们更多有关您的错误的信息,例如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 进行此symfony会自动调用此类以序列化Fichier实体,并且您可以在

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 然后将其添加到您的services.yml文件中

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

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

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