【问题标题】:Symfony serialized Response vs normalized JsonResponseSymfony 序列化响应与标准化 JsonResponse
【发布时间】:2017-06-29 13:47:00
【问题描述】:

我正在构建一个 API,它需要将一些实体输出为 JSON。我试图弄清楚是否最好将实体规范化并将其传递给JsonResponse,或者我是否应该将其序列化并将其传递给Response。两者有什么区别?

/**
 * Returning a Response
 */
public function getEntityAction($id)
{
    $entity = $this->getDoctrine()->getRepository(MyEntity::class)->find($id);

    $json = $this->get('serializer')->serialize($entity);
    $response = new Response($json);
    $response->headers->set('Content-Type', 'application/json');

    return $response
}

/**
 * Returning a JsonResponse.
 */
public function getEntityAction($id)
{
    $entity = $this->getDoctrine()->getRepository(MyEntity::class)->find($id);

    $array = $this->get('serializer')->normalize($entity);
    return new JsonResponse($array);
}

除了我不必为JsonResponse 手动设置Content-Type 标头之外,两者之间是否有任何实际区别?

【问题讨论】:

    标签: php json symfony


    【解决方案1】:

    您可以将 Serializer 使用的编码器:JsonEncodeJsonResponse 所做的比较。本质上是一样的。在后台都使用json_encode 来生成字符串。

    我想任何适合您项目的东西都是不错的选择。 JsonResponse 主要是为了方便起见,正如您已经指出的那样,它将自动设置正确的 Content Type-header 并为您进行 json 编码。

    【讨论】:

    • 你是对的。我确实看过他们早些时候做了什么,但我挖得更深了。 JsonResponse 设置了一些 encoding options,这使得编码 HTML 变得安全。它还设置了Content-Type 标头。所以我想我会使用 JsonEncode,这样我就不必自己做这些事情了。
    【解决方案2】:

    根据我对 Symfony 序列化的理解,规范化是序列化过程的一部分,其中对象被映射到关联数组,然后将该数组编码为纯 JSON 对象,完成序列化。

    您使用 normalize 函数的代码实际上可以修改为使用 Response 类而不是 JsonResponse:

    /**
     * Returning a JsonResponse.
     */
    public function getEntityAction($id)
    {
        $entity = $this->getDoctrine()->getRepository(MyEntity::class)->find($id);
    
        $array = $this->get('serializer')->normalize($entity);
        $response = new Response(json_encode($array));
        $response->headers->set('Content-Type', 'application/json');
        return $response;
    }
    

    我没有检查序列化函数的 Symfony 代码,但相信其中一部分将是规范化函数。你可以在 symfony 文档中找到解释:http://symfony.com/doc/current/components/serializer.html

    【讨论】:

    • 是的,我知道我可以做到。我更关注每种数据序列化方式的具体差异(优点/缺点)。
    猜你喜欢
    • 2017-02-25
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 2019-04-27
    • 2013-11-25
    • 2017-03-30
    • 2021-03-03
    • 2014-05-22
    相关资源
    最近更新 更多