Class JsonResponse.
Description
Provides a JSON-specific HTTP response implementation that complies with PSR-7 Response interfaces. This class MUST be used when returning JSON payloads over HTTP responses. It automatically sets the 'Content-Type' header to 'application/json' with the specified charset.
Interfaces
Methods
Constructs a new JsonResponse instance with an optional payload and charset.
Retrieves the payload contained in the response body.
Returns an instance with the specified payload.
Constructs a new JsonResponse instance with an optional payload and charset.
public
__construct([
mixed
$payload = []][,
string
$charset = 'utf-8'][,
array<string|int, mixed>
$headers = []]) : mixed
Description
This constructor SHALL initialize the response body with a JsonStream containing the provided payload. The 'Content-Type' header MUST be set to 'application/json' with the specified charset.
Parameters
$payload
:
mixed
=
[]
Description
The JSON-serializable payload to send in the response body. Defaults to an empty array.
$charset
:
string
=
'utf-8'
Description
The character encoding to use in the 'Content-Type' header. Defaults to 'utf-8'.
$headers
:
array<string|int, mixed>
=
[]
public
getBody() : PayloadStreamInterface
Description
Retrieves the response body as a JSON stream.
Return values
Retrieves the payload contained in the response body.
public
getPayload() : mixed
Description
This method MUST return the same payload provided during construction or via withPayload().
Return values
Description
the decoded JSON payload
Returns an instance with the specified payload.
public
withPayload(
mixed
$payload) : self
Description
This method SHALL return a new instance of the response with the body replaced by a new JsonStream containing the provided payload. The original instance MUST remain unchanged, ensuring immutability as required by PSR-7.
Parameters
$payload
:
mixed
Description
the new JSON-serializable payload
Return values
Description
a new JsonResponse instance with the updated payload