Skip to content

JsonResponse

github-actions edited this page Mar 29, 2026 · 1 revision

Class JsonResponse.

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.


Methods

__construct

Constructs a new JsonResponse instance with an optional payload and charset.

public __construct(mixed $payload = [], string $charset = 'utf-8', array $headers = []): mixed

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:

Parameter Type Description
$payload mixed The JSON-serializable payload to send in the response body. Defaults to an empty array.
$charset string The character encoding to use in the 'Content-Type' header. Defaults to 'utf-8'.
$headers array

getPayload

Retrieves the payload contained in the response body.

public getPayload(): mixed

This method MUST return the same payload provided during construction or via withPayload().

Return Value:

the decoded JSON payload


withPayload

Returns an instance with the specified payload.

public withPayload(mixed $payload): self

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:

Parameter Type Description
$payload mixed the new JSON-serializable payload

Return Value:

a new JsonResponse instance with the updated payload


Clone this wiki locally