将对象序列化为ZF3 MVC Response JSON

时间:2017-02-07 19:46:52

标签: 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;

    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:需要一个数组或Traversable参数;收到" Application \ Model \ HelloObjectResponse"

如何以zend知道设置mime类型及其所有内容的方式轻松创建该对象JSON。

1 个答案:

答案 0 :(得分:2)

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