Skip to content

JsonResponse

github-actions[bot] edited this page Oct 24, 2026 · 2 revisions

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.

A body replaced through PSR-7 withBody() may be any StreamInterface.


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

Original payload streams return their stored payload. Generic readable, seekable streams are decoded as associative JSON without changing the cursor. Invalid JSON throws JsonException; unreadable, detached or non-seekable generic streams throw RuntimeException rather than being consumed.

Return Value:

the decoded JSON payload

Throws:


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