I have problem with my Symfony rest API. I have this controller:
<?php
namespace App\Controller;
use App\Entity\Post;
use App\Service\ErrorDecoratorService;
use App\Service\PostService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Serializer\SerializerInterface;
class PostController extends AbstractController
{
private $postService;
private $errorDecoratorService;
public function __construct(PostService $postService, ErrorDecoratorService $errorDecoratorService)
{
$this->postService = $postService;
$this->errorDecoratorService = $errorDecoratorService;
}
/**
* @Route("/post/{postId}", methods={"GET"})
* @param $postId
* @param SerializerInterface $serializer
* @return JsonResponse
*/
public function getPost($postId, SerializerInterface $serializer)
{
$result = $this->postService->getPost($postId);
if ($result instanceof Post) {
$data = $serializer->serialize($result,'json');
$status = JsonResponse::HTTP_OK;
} else {
$status = JsonResponse::HTTP_NOT_FOUND;
$data = $this->errorDecoratorService->decorateError($status, $result);
}
return new JsonResponse($data, $status);
}
}
When I have from database serialize to JSON format, then I receive this error:
Could not normalize object of type App\Entity\Post, no supporting normalizer found. (500 Internal Server Error)
It's my entity
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity(repositoryClass="App\Repository\PostRepository")
*/
class Post
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
* @Assert\NotBlank()
*/
private $title;
/**
* @ORM\Column(type="string", length=255)
* @Assert\NotBlank()
*/
private $content;
/**
* @ORM\Column(type="string", length=255)
* @Assert\NotBlank()
*/
private $author;
public function getId(): ?int
{
return $this->id;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
public function getContent(): ?string
{
return $this->content;
}
public function setContent(string $content): self
{
$this->content = $content;
return $this;
}
public function getAuthor(): ?string
{
return $this->author;
}
public function setAuthor(string $author): self
{
$this->author = $author;
return $this;
}
}
Where is my mistake? I have tried Symfony Serializer, JMS Serializer but I still get the same error.