3

我为 JMS 序列化配置了一个访问者:

class MyHandler implements SubscribingHandlerInterface
{

public static function getSubscribingMethods()
{
    return array(
        array(
            'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
            'format' => 'json',
            'type' => 'MyObject',
            'method' => 'serializeContextParent',
        ),
    );
}

public function serializeContextParent(JsonSerializationVisitor $visitor, $data, array $type, Context $context)
{
    if (in_array('id', $type['params']))
        return $data->getId();

    // Do default deserialization ???
}

}

我只想在有参数 id 时反序列化 MyObject 的 id(所以声明的类型是 @JMS\Type("MyObject<'id'>")。

效果很好,但是,如果找不到参数,我想继续默认反序列化。

那可能吗 ?

谢谢

4

1 回答 1

0

Simply use a different Object type for the special case:

class MyObject {
    /**
     * @var User
     * @JMS\Type("User")
     * /
    protected $user;
    /**
     * @var User
     * @JMS\Type("UserWithId")
     * /
    protected $userWithId;
}

And the handler can be something as:

class MyHandler implements SubscribingHandlerInterface
{

public static function getSubscribingMethods()
{
    return array(
        array(
            'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
            'format' => 'json',
            'type' => 'UserWithId',
            'method' => 'serializeContextParent',
        ),
    );
}

public function serializeContextParent(JsonSerializationVisitor $visitor, $data, array $type, Context $context)
{
    return $data->getId();
}

}

Since you know if the user has the id or not (you were using a type parameter), you can instead use just a custom type name.

...and since is possible to add custom handlers on custom type, the solution should work

于 2017-02-21T14:22:23.410 回答