【问题标题】:Symfony JsonResponse with Serializer带有序列化器的 Symfony JsonResponse
【发布时间】:2017-02-25 15:34:31
【问题描述】:

我有一个小问题。也许有人有一个想法。

我通过以下方式使用 Serializer。函数 json_encode 应用两次的问题。

首先当我调用 $serializer->serialize($post, 'json');

第二次在$response->setData();

所以,要解码,我需要调用两次函数。

有什么想法吗?

$encoders = [
    new JsonEncoder()
];
$normalizer = new ObjectNormalizer();
$normalizer->setCircularReferenceHandler(function ($object) {
    return $object->getId();
});
$normalizers = [$normalizer];
$serializer  = new Serializer($normalizers, $encoders);

$response = new JsonResponse();
$response->setData([
    'status' => true,
    'data'   => $serializer->serialize($post, 'json')
]);

return $response;

【问题讨论】:

  • 'data' => $post?
  • 然后我在编码我的实体和循环引用时遇到了问题。即使实体实现了 JsonSerializable。

标签: php json symfony


【解决方案1】:

该对象被编码两次,因为您使用的是 jsonresponse,请改用简单的响应。另外对整个数据进行编码,而不仅仅是其中的一部分。例如:

$responseData = [
    'status' => true,
    'data'   => $post
];

$response = new Response(
   $serializer->serialize($$responseData, 'json'),
   Response::HTTP_OK,
   ['Content-type' => 'application/json']
);

return $response:

希望有帮助

【讨论】:

  • 谢谢。找到在 PersistantCollection 调用 getValues() 的解决方案。并在实体中实现 JsonSerializable。没有序列化器。
  • 如何在响应中添加参数?喜欢'success' => true
【解决方案2】:

要返回 json string 而不是 array,请使用 JsonResponse::fromJsonString 方法:

return JsonResponse::fromJsonString($serializer->serialize($data, 'json'));

【讨论】:

    【解决方案3】:

    这是一个“纯”的 symfony 答案,带有 JsonResponse 助手:

    $doctors= $this->doctorsRepository->findBy_Name("dummy name"); // returns "Result" and NOT an "ArrayResult"
    
    return new JsonResponse(
        $serializer->serialize($doctors, 'json', [
            ObjectNormalizer::GROUPS => ['for_importing_some_specific_fields']
        ]), // your serialized json but as a 'string' json
        200, // equivalent code for Response::HTTP_OK (success) 
        [], // headers (by default it is application/json because of the Jsonresponse class)
        true // already a json string so convert it to a json Object
    );
    

    【讨论】:

      猜你喜欢
      • 2017-06-29
      • 2014-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-13
      • 1970-01-01
      • 2017-03-30
      • 2021-03-03
      相关资源
      最近更新 更多