Returning JSON from a ZF2 controller action

The new view layer in Zend Framework 2 can be set up to return JSON rather than rendered HTML relatively easily. There are two steps to this:

Set up the JsonStrategy

Firstly we need to set up the view's JsonStrategy to check to a situation when returning JSON is required and then to render out JSON for us. The JsonStrategy will cause the JsonRenderer to be run in two situations:

  1. The view model returned by the controller action is a JsonModel
  2. The HTTP Accept header sent in the Request include "application/json"

To enable the JsonStrategy, we simply configure it in the module's config.php file:

module/Application/config/module.config.php:

As you can see, in the view_manager() add ViewJsonStrategy to the strategies array.

Return a JsonModel from the controller action

To send JSON to the client when the Accept header isn't application/json, we use a JsonModel in a controller action like this:

module/Application/src/Application/Controller/IndexController.php:

The output will now be JSON. Obviously, if you're sending JSON back based on the Accept header, then you can return a normal ViewModel.

Note that this entry was updated on 20 June 2012 to reflect updates to ZF2.

See also: Returning JSON using the Accept header in ZF2