Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 将对象序列化为ZF3 MVC响应JSON_Php_Zend Framework Mvc_Zend Framework3 - Fatal编程技术网

Php 将对象序列化为ZF3 MVC响应JSON

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;

我有一个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;
    }
}

这给了我一个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));