Zend Framework 2 - Return JSON from Controller
json, php, zend-framework2
Solution
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
Problem
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