[英]Symfony JsonResponse with Serializer
I have a small problem.我有一个小问题。 Maybe someone have an a idea.
也许有人有一个想法。
I use Serializer in the following way.我按以下方式使用序列化程序。 The problem that function json_encode is applied two times.
函数 json_encode 被应用两次的问题。
First when i call $serializer->serialize($post, 'json');首先当我调用 $serializer->serialize($post, 'json');
Second time in $response->setData();第二次在 $response->setData();
So, to decode i need call function two times.所以,要解码我需要调用函数两次。
Any ideas?有什么想法吗?
$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;
The object is encoded twice because you use a jsonresponse, use a simple response instead.该对象被编码两次,因为您使用了 jsonresponse,请改用简单的响应。 In addition encode the entire data, not only part of them .
另外对整个数据进行编码,而不仅仅是其中的一部分。 As example:
例如:
$responseData = [
'status' => true,
'data' => $post
];
$response = new Response(
$serializer->serialize($$responseData, 'json'),
Response::HTTP_OK,
['Content-type' => 'application/json']
);
return $response:
Hope this help希望这有帮助
要返回 json string
而不是array
使用JsonResponse::fromJsonString
方法:
return JsonResponse::fromJsonString($serializer->serialize($data, 'json'));
Here is a "pure" symfony answer, with the JsonResponse helper :这是一个“纯”的 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
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.