【问题标题】:Return array of serialized data in Symfony 4在 Symfony 4 中返回序列化数据数组
【发布时间】:2019-04-10 13:42:57
【问题描述】:

Symfony 4. 我有 2 个实体,CatDog,它们需要被序列化,然后作为 JSON 响应返回,如下所示:

{
  'cats': // array of serialized cat data
  'dogs': // array of serialized dog data
}

这是我目前所拥有的:

控制器:

public function index()
{
    $repository = $this->getDoctrine()->getRepository(Cat::class);
    $cats = $repository->findAll();
    $repository = $this->getDoctrine()->getRepository(Dog::class);
    $dogs = $repository->findAll();
    return new JsonResponse([
        'cats' => $this->serializeData($cats, 'cats'),
        'dogs' => $this->serializeData($dogs, 'dogs'),
    ], 200);
}

而我的serializeData 方法如下所示:

protected function serializeData($data, $group)
{
    return $this->json($data, $this->statusCode, [], [
        'groups' => [$group]
    ]);
}

这是Cat 实体的一点点:

use Symfony\Component\Serializer\Annotation\Groups;
[...]
/**
 * @ORM\Entity(repositoryClass="App\Repository\CatRepository")
 */
class Cat
{
    [...]
    /**
     * @ORM\Column(type="string", length=255)
     * @Groups("cats")
     */
    private $name;
    [...]
}

问题:当到达这个端点时,而不是我得到的数据:

{
    "cats": {
        "headers": {}
    },
    "dogs": {
        "headers": {}
    }
}

headers 不属于任一实体。

编辑:

我还尝试了什么:

public function index()
{
    $repository = $this->getDoctrine()->getRepository(Cat::class);
    $cats = $repository->findAll();
    $repository = $this->getDoctrine()->getRepository(Dog::class);
    $dogs = $repository->findAll();
    return new JsonResponse([
        'cats' => $this->container->get('serializer')->serialize($cats, 'json', [
            'groups' => ['cats'],
        ])
        'dogs' => $this->container->get('serializer')->serialize($dogs, 'json', [
            'groups' => ['dogs'],
        ])
    ], 200);
}

这种工作,但new JsonResponse 序列化已经序列化的猫和狗。当然,如果我将 new JsonResponse 替换为 new Response 我会得到错误

响应内容必须是实现__toString()的字符串或对象,给定“数组”。

【问题讨论】:

    标签: php symfony serialization


    【解决方案1】:

    您可以使用 Symfony Serializer 组件:

    https://symfony.com/doc/master/components/serializer.html

    【讨论】:

    • 谢谢 - 在我的问题的编辑中,我已经展示了当我直接使用序列化程序时会发生什么。
    【解决方案2】:

    好吧,方法 $this->json 返回一个 JsonResponse 所以整个东西都返回一个 JsonResponse(JsonResponse...) - source

    public function index()
    {
    ...
        return $this->json(['cats' => $cats, 'dogs' => $dogs], 200, [], ['groups' => ['cats', 'dogs']]);
    }
    

    【讨论】:

    • 如果我删除 @group 注释,我将删除 @group 注释提供的功能,因为我需要它,所以我把它放在那里。
    • 好吧,所以我认为你需要自己结合它。查看源代码,您将了解序列化程序的使用方式 - 只需序列化 $cats 和 $dogs。我会尝试在几分钟内更新帖子 - 但我无法检查它
    • 感谢您的坚持,我已经编辑了我的答案,以显示当我遵循您的方法时会发生什么。
    • 你在控制器的动作方法中有一些注解吗?
    • 我不想再浪费你的时间了,我认为我的用例有点小众,而且篇幅太长,无法在一篇文章中解释。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    相关资源
    最近更新 更多