Symfony Serializer issue - NotNormalizableValueException

元气小坏坏 提交于 2020-02-03 11:38:28

问题


I have an issue when I'm using the serializer with FOSRestBundle in Symfony 4.1

I have the following error message :

Could not normalize object of type App\Entity\Youp, no supporting normalizer found. Symfony\Component\Serializer\Exception\NotNormalizableValueException

I don't understand why I have this issue, Symfony's Serializer should have an serializer object or I miss something ?

See bellow my controller and my entity :

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\YoupRepository")
 */
class Youp
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

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

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }
}

<?php 

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;

use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\View\View;
use FOS\RestBundle\Controller\Annotations as Rest;

use App\Entity\Youp;

class BidonController extends FOSRestController {

  /**
   * @Rest\View()
   * @Rest\Get("/youps")
   */
  public function getPharmacies() {
    $youps = $this->getDoctrine()->getRepository(Youp::class)->findAll();
    return $youps; 
  }
}

回答1:


Your object's properties are private so the serializer doesn't know how to normalize or get any data from your object. You can either set the properties to public or enable the ObjectNormalizer (which uses the PropertyAccess Component to access the private/protected properties) and/or GetSetMethodNormalizer (which reads the content of the class by calling the "getters") using the following service-definition in your configuration:

services:
  # [..]
  Symfony\Component\Serializer\Normalizer\ObjectNormalizer:
    class: Symfony\Component\Serializer\Normalizer\ObjectNormalizer
    public: false
    tags:
      - { name: 'serializer.normalizer' }

  Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer:
    class: Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer
    public: false
    tags:
      - { name: 'serializer.normalizer' }

Clear your cache afterwards. More information about the normalizers already included in the serializer component can be found in the documentation



来源:https://stackoverflow.com/questions/52861597/symfony-serializer-issue-notnormalizablevalueexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!