Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zend Framework 2 - Return JSON from Controller

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

like image 294
Jake Avatar asked Dec 20 '22 18:12

Jake


1 Answers

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

like image 134
Danizord Avatar answered Dec 24 '22 01:12

Danizord