【问题标题】:Serialize data from database序列化数据库中的数据
【发布时间】: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

标签: serialization symfony4


【解决方案1】:

一旦你enable the Normalizer,Serializer 将生成一个 json 编码的 string,其中包含以下行:

$data = $serializer->serialize($result,'json'); 
// "{\"id\":1,\"title\":\"qwerty\",\"content\":\"Lorem ipsum sit dolor amet\",\"author\":\"Pawel\"}"

JsonResponse 构造 json 编码第一个参数,通常是数组或对象,但在您的情况下只是一个 字符串。您需要在将字符串传递给构造函数时对其进行解码,或者最好使用JsonResponse::fromJsonString() 方法。

应该工作:

return new JsonResponse(json_decode($data), $status);

首选方法:

return new JsonResponse::fromJsonString($data, $status);

https://symfony.com/doc/current/components/http_foundation.html#creating-a-json-response

【讨论】:

  • 现在我的pastebin.com/cJjUFV9i 工作正常,但是这段代码好吗?这是一个很好的解决方案?肯定会工作。
  • 如果它适合你,那应该没问题。然而,我提供的首选方法将是更好的性能,因为它不需要进行任何编码/解码,并且在我看来它的语义更好。
猜你喜欢
  • 2011-10-12
  • 1970-01-01
  • 1970-01-01
  • 2011-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-22
  • 2012-05-17
相关资源
最近更新 更多