Php 将对象序列化为ZF3 MVC响应JSON
我有一个Zend Framework 3应用程序。我将Php 将对象序列化为ZF3 MVC响应JSON,php,zend-framework-mvc,zend-framework3,Php,Zend Framework Mvc,Zend Framework3,我有一个Zend Framework 3应用程序。我将ViewJsonStrategy添加到module.config.php。这允许以下端点返回JSON: public function helloAction() { return new JsonModel([ 'msg'=> 'Hello World!', ]); } 但是,我想返回对象 class HelloObjectResponse { protected $message;
ViewJsonStrategy
添加到module.config.php
。这允许以下端点返回JSON:
public function helloAction() {
return new JsonModel([
'msg'=> 'Hello World!',
]);
}
但是,我想返回对象
class HelloObjectResponse
{
protected $message;
public function getMessage() : string {
return $this->message;
}
public function setMessage(string $message) : self {
$this->message = $message;
return $this;
}
}
这给了我一个Zend错误消息 Zend\View\Model\ViewModel::setVariables:需要一个数组或可遍历的参数;收到“应用程序\模型\ HelloObject响应”
我如何以zend知道的设置mime类型和所有这些的方式轻松地创建对象JSON。这就是答案。在仔细考虑之后,我可能正在做一些稍微不同的事情。
use Zend\View\Model\JsonModel;
use Zend\Hydrator\Reflection;
$obj = new HelloObjectResponse();
$obj->setMessage('Hello World!');
$hydrator = new Reflection;
return new JsonModel($hydrator->extract($obj));
use Zend\View\Model\JsonModel;
use Zend\Hydrator\Reflection;
$obj = new HelloObjectResponse();
$obj->setMessage('Hello World!');
$hydrator = new Reflection;
return new JsonModel($hydrator->extract($obj));