启用处理程序时来自 JMS 序列化程序的 NULL 响应



(Symfony + JMS Serializer(

我有以下服务:

my_serializer:
        class: MySerializer
        tags:
            - { name: jms_serializer.handler, type: MyClass, direction: serialization, format: json, method: serializeMyClassToJson }

服务类仅包含一个方法:

public function serializeMyClassToJson(
    JsonSerializationVisitor $visitor,
    MyClass $myObject,
    array $type,
    Context $context
) {
    return array(
        'id' => $myObject->getId()
         // .. and so on
    );
}

启用处理程序时,在此类的任何对象上调用 serialize() 时,我得到一个 NULL 结果(即在 JMS 序列化程序中注册 - 如果我删除它,一切正常(:

$this->container->get('jms_serializer')->serialize($myObject, 'json'); // null

需要注意的几点:

  1. 调用了我的序列化方法,我确定我从中返回了正确的数组(显然,我用几个虚拟数组进行了测试 - 但结果是相同的(。

  2. 奇怪的是,当MyClass是不同的 Doctrine 托管实体的一部分并且我序列化该实体时,序列化有效(MySecondClassMyClassOneToOne关系(:

    [...]->serialize($mySecondObject, 'json'); // includes the correct JSON result for $myObject
    [...]->serialize($mySecondObject->getMyObject(), 'json'); // null
    
  3. 我没有为 MyClass 中的属性定义任何注释。

那么,可能我缺少处理程序的一些注释或回调?

一种解决方法(虽然不是我问题的答案(似乎是对我的处理程序回调进行以下调整:

public function serializeMyClassToJson(
    JsonSerializationVisitor $visitor,
    MyClass $myObject,
    array $type,
    Context $context
) {
    $result = array(
        'id' => $myObject->getId()
         // .. and so on
    );
    // Populate the root element if it's NULL
    // (with this change, the JSON output seems to be correct)
    if ($visitor->getRoot() === null) {
        $visitor->setRoot($result);
    }
    return $result;
}

相关内容

最新更新