4

I have the following Json String:

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

I am trying to use ZF2's JsonModel class (Zend\View\Model\JsonModel) in the controller to render my view with the above JSON string. However, it seems to take only an array instead of a JSON String.

How do I make the controller return a JSON string?

Thanks

4 Answers 4

7

You don't need to use a JsonModel since your json is already "rendered", so, you can set it directly in 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;
}

That will short-circuit the dispatch event, so the application will return your response immediately, without calling the view layer to render it.

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

Sign up to request clarification or add additional context in comments.

Comments

2

You have to use the acceptableViewModelSelector controller plugin

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));
}

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

Comments

1

Another bonus : explanation of why using this plugin

JsonStrategy security fix

Comments

1

Add in module.config.php:

'strategies' => [
     'ViewJsonStrategy',
 ],

Then you can return in controller json response:

return new JsonModel(['some'=>'data']);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.