diff --git a/components/http_foundation.rst b/components/http_foundation.rst index 03f054412e4..225726ab550 100644 --- a/components/http_foundation.rst +++ b/components/http_foundation.rst @@ -547,13 +547,22 @@ class, which can make this even easier:: use Symfony\Component\HttpFoundation\JsonResponse; + // if you know the data to send when creating the response + $response = new JsonResponse(array('data' => 123)); + + // if you don't know the data to send when creating the response $response = new JsonResponse(); - $response->setData(array( - 'data' => 123 - )); + // ... + $response->setData(array('data' => 123)); + + // if the data to send is already encoded in JSON + $response = JsonResponse::fromJsonString('{ "data": 123 }'); + +.. versionadded:: 3.2 + The ``JsonResponse::fromJsonString()`` method was added in Symfony 3.2. -This encodes your array of data to JSON and sets the ``Content-Type`` header -to ``application/json``. +The ``JsonResponse`` class sets the ``Content-Type`` header to +``application/json`` and encodes your data to JSON when needed. .. caution::