【发布时间】:2020-01-05 01:25:21
【问题描述】:
我的 Symfony REST API 有问题。我有这个控制器:
<?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);
}
}
当我从数据库序列化为 JSON 格式时,我收到此错误:
无法规范化 App\Entity\Post 类型的对象,不支持 找到归一化器。 (500 内部服务器错误)
这是我的实体
<?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;
}
}
我的错误在哪里?我已经尝试过 Symfony 序列化器、JMS 序列化器,但我仍然得到同样的错误。
【问题讨论】:
-
当我在谷歌搜索你的错误信息时,这是第一个结果stackoverflow.com/a/52861797/6127393
-
@ArleighHix 我会检查这个结果
-
@ArleighHix 当我使用游览链接并添加服务时,作为响应我有 "{\"id\":1,\"title\":\"qwerty\",\"content\ ":\"Lorem ipsum sit dolor amet\",\"author\":\"Pawel\"}" 当我将此代码粘贴到 json 验证器中时,它表明它不是有效的 json