将对象序列化为 ZF3 MVC 响应 JSON
Serializing objects to ZF3 MVC Response JSON
我有一个 Zend Framework 3 应用程序。我将 ViewJsonStrategy
添加到 module.config.php
。这让以下端点 return JSON:
public function helloAction() {
return new JsonModel([
'msg'=> 'Hello World!',
]);
}
不过,我想return对象
class HelloObjectResponse
{
protected $message;
public function getMessage() : string {
return $this->message;
}
public function setMessage(string $message) : self {
$this->message = $message;
return $this;
}
}
public function helloObjectAction() {
$obj = new HelloObjectResponse();
$obj->setMessage('Hello World!');
return new JsonModel($obj);
}
这给了我一个 Zend 错误消息。
Zend\View\Model\ViewModel::setVariables: expects an array, or Traversable argument; received "Application\Model\HelloObjectResponse"
如何以 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));
我有一个 Zend Framework 3 应用程序。我将 ViewJsonStrategy
添加到 module.config.php
。这让以下端点 return JSON:
public function helloAction() {
return new JsonModel([
'msg'=> 'Hello World!',
]);
}
不过,我想return对象
class HelloObjectResponse
{
protected $message;
public function getMessage() : string {
return $this->message;
}
public function setMessage(string $message) : self {
$this->message = $message;
return $this;
}
}
public function helloObjectAction() {
$obj = new HelloObjectResponse();
$obj->setMessage('Hello World!');
return new JsonModel($obj);
}
这给了我一个 Zend 错误消息。
Zend\View\Model\ViewModel::setVariables: expects an array, or Traversable argument; received "Application\Model\HelloObjectResponse"
如何以 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));