Zend Framework 2 - Returns JSON from the controller

I have the following Json line:

var jsonString = '{"Users":[{"Name":"abc","Value":"test"},{"Name":"def","Value":"test"}]}';

I am trying to use the ZF2 JsonModel class (Zend \ View \ Model \ JsonModel) in a controller to display my view with the above JSON string. However, instead of a JSON string, it seems that only an array is required.

How to make the controller return a JSON string?

thank

+3
source share
3 answers

You do not need to use JsonModel, since your json is already "displayed", so you can set it directly in the response object and return it:

/**
 * @return \Zend\Http\Response
 */
public function indexAction()
{
    $json = '{"Users":[{"Name":"abc","Value":"test"},{"Name":"def","Value":"test"}]}';

    $this->response->setContent($json);

    return $this->response;
}

This will lead to a short circuit in the send event, so the application will immediately return your response without naming the view layer to display it.

. http://framework.zend.com/manual/2.2/en/modules/zend.mvc.examples.html#returning-early

+5

acceptableViewModelSelector

public function listAction()
{
    $acceptCriteria = array(
    'Zend\View\Model\ViewModel' => array(
        'text/html',
    ),
    'Zend\View\Model\JsonModel' => array(
        'application/json',
    ));

    $viewModel = $this->acceptableViewModelSelector($acceptCriteria);

    Json::$useBuiltinEncoderDecoder = true;

    $itemsList = $this->getMyListOfItems();

    return $viewModel->setVariables(array("items" => $itemsList));
}

: http://framework.zend.com/manual/2.2/en/modules/zend.mvc.plugins.html#zend-mvc-controller-plugins-acceptableviewmodelselector

+2

Another bonus: an explanation of why using this plugin

JsonStrategy Security Patch

+1
source

All Articles