How can I do json response from controller's action in cakephp-4?

Hello, How can I do json response from controller’s action in cakephp-4?

 header('Content-Type: application/json');
        echo json_encode($statess);
        exit();

Or
$this->set('countries', $countries);

Don’t echo output directly in your controller! Use things like withStringBody in the response object. Here’s an exact example of what you’re trying to do.

What is $response here? How to declare $response?

Can you please paste complete code with $this->set?

If you are using withStringBody, then there is no $this->set required. The response object is thoroughly documented elsewhere on that same page I linked to. $response is a generic example, in your controller you’d use return $this->response-withStringBody(...)

maybe it helps:
i have a live-search and return the results from controller with:
return $this->response->withType(‘application/json’)->withStringBody(json_encode($resulltsArr));