JSON view not working

I am trying to output json view (without the need of a template) in my Cake5 controller.

Base on JSON Docs, my code is similar. but i am still getting the error ‘no template’.

Am I missing something ?

// My controller file. No template files has been created.

    public function initialize(): void {
        parent::initialize();

        $this->addViewClasses([JsonView::class, ]);

    }


    public function viewClasses(): array
    {
        return [JsonView::class];
    }

    public function testJsonView()
    {
        $articles = ['test view'];
        // Set the view vars that have to be serialized.
        $this->set(compact('articles', ));

        // Specify which view vars JsonView should serialize.
        $this->viewBuilder()->setOption('serialize', ['articles', ]);
    }

Your request needs to have set the Accept HTTP Header to application/json
Otherwise Cake won’t render your request as such.

See https://www.youtube.com/watch?v=GZPUlQEnAkA

Thanks.

without specifying the extension .json, is there a way to ‘force’ it to JSON view in a GET request ?

In the previous version of Cake, this worked for me

        $this->RequestHandler->renderAs($this, 'json');
        $this->response->withType('application/json');
        $this->set('_serialize', true);

Just manually set the view class instead of relying on cake to do it for you.

$test = "test";
$this->set(compact('test'));
$this->viewBuilder()
    ->setOption('serialize', ['test'])
    ->setClassName('Json');

This allows you to choose a view by the client requesting it e.g. http://yourhost/videos/export/json

https://book.cakephp.org/4/en/views/json-and-xml-views.html#choosing-a-view-class