Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/symfony/6.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 JMS序列化程序无法将对象序列化为数组_Php_Symfony_Jmsserializerbundle_Jms Serializer - Fatal编程技术网

Php JMS序列化程序无法将对象序列化为数组

Php JMS序列化程序无法将对象序列化为数组,php,symfony,jmsserializerbundle,jms-serializer,Php,Symfony,Jmsserializerbundle,Jms Serializer,我有一个只用作数组容器的类 class Container { private $things = array(); public function addThing($thing) { $this->things[] = $thing; return $this; } public function getThings() { return $this->things; } } 我想使用

我有一个只用作数组容器的类

class Container {
    private $things = array();

    public function addThing($thing) {
        $this->things[] = $thing;

        return $this;
    }

    public function getThings() {
        return $this->things;
    }
}
我想使用JMS\Serializer将这个类序列化为它所包含的数组。为此,我使用了一个特殊的处理函数:

use JMS\Serializer\Annotation\HandlerCallback;

class Container {
    // ...

    /**
     * @HandlerCallback("json", direction = "serialization")
     */
    public function serializeToJson() {
        return $this->things;
    }
}
现在如果我跑

$container = new Container();
$container->addThing('something'); // optional
print_r($serializer->serialize($container, 'json'));
我的期望是

[
    'something'
]
但是我得到的是
null

我已经报告了这个问题,但是有人知道这个问题的解决方法吗?我应该如何解决这个问题(不使用
@HandlerCallback
或其他想法)以获得期望的结果


谢谢

尝试使用作为方法参数传递的访问者对象,如下所示:

/** @HandlerCallback("json", direction = "serialization") */
public function serializeToJson(JsonSerializationVisitor $visitor)
{
    $visitor->addData($this->things);
}

希望此帮助

据我所知,
addData()
接受2个参数并添加到
$visitor
中的关联数组中。我想单独返回
$things
数组,而不是包含在另一个数组中。不管怎样,我已经试过了,它在寻找第二个参数时抛出了一个错误。如果我在
$this->things
之前放置一个键,序列化结果仍然是
null
。您好@tetele您是对的,正确的签名是
addData($key,$value)
您是否尝试过类似
$visitor->addData('things',$this->things)的东西?否则,您也可以尝试使用
$visitor->setRoot($this->things)