Skip to content

Commit f89a45f

Browse files
committed
minor #14903 [HttpFoundation] JsonResponse content updated (MehGokalp)
This PR was submitted for the 5.2 branch but it was merged into the 4.4 branch instead. Discussion ---------- [HttpFoundation] JsonResponse content updated When using the `JsonResponse` with customized encoding options, the `JsonResponse` class can modify the given data. Example: ```php $response = new JsonResponse(['data' => (float) 3]); echo $response->getContent(); // {"data": 3} $response->setEncodingOptions(JsonResponse::DEFAULT_ENCODING_OPTIONS | \JSON_PRESERVE_ZERO_FRACTION); echo $response->getContent(); // {"data": 3} ``` as you can see we gave float value and it returns integer. Because when we instantiate the `JsonResponse` it serializes the data with default encoding options. The proper way to do this; ```php $response = new JsonResponse(); $response->setEncodingOptions(JsonResponse::DEFAULT_ENCODING_OPTIONS | \JSON_PRESERVE_ZERO_FRACTION); $response->setData(['data' => (float) 3]); echo $response->getContent(); // {"data": 3.0} ``` for details of the \JSON_PRESERVE_ZERO_FRACTION flag see [https://www.php.net/manual/en/function.json-encode.php](https://www.php.net/manual/en/function.json-encode.php) Commits ------- 367efdb JsonResponse content updated
2 parents e16bc4e + 367efdb commit f89a45f

File tree

1 file changed

+3
-1
lines changed

1 file changed

+3
-1
lines changed

components/http_foundation.rst

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -668,9 +668,11 @@ class, which can make this even easier::
668668
// if you know the data to send when creating the response
669669
$response = new JsonResponse(['data' => 123]);
670670

671-
// if you don't know the data to send when creating the response
671+
// if you don't know the data to send or if you want to customize the encoding options
672672
$response = new JsonResponse();
673673
// ...
674+
// configure any custom encoding options (if needed, it must be called before "setData()")
675+
//$response->setEncodingOptions(JsonResponse::DEFAULT_ENCODING_OPTIONS | \JSON_PRESERVE_ZERO_FRACTION);
674676
$response->setData(['data' => 123]);
675677

676678
// if the data to send is already encoded in JSON

0 commit comments

Comments
 (0)