jms 序列化程序包序列化超级 class

jms serializer bundle serialize super class

我使用 jms 序列化程序包序列化一个超级 class 但我想像这样序列化我的超级 class:

/**
 * @Discriminator(field = "type", map = {"vehicle": "Vehicle", "car": "Car", "moped": "Moped"})
 */
class Vehicle { }
class Car extends Vehicle { }
class Moped extends Vehicle { }

但它不起作用我可以在我的 json 中为儿童开火 'type' 但不能为我的超级 class 车辆开火。 我立即使用黑客:

$data = $this->serializer->serialize($vehicle, 'json');
if(!strpos(",\"type\":", $data))
{
    $data = substr_replace($data ,",\"type\":\"vehicle\"}",-1);
}

添加我的字段,然后可以反序列化我的对象。

您对此有更清晰的想法吗?

根据文档:

@Discriminator This annotation allows deserialization of relations which are polymorphic, but where a common base class exists. The @Discriminator annotation has to be applied to the least super type.

恐怕您对此无能为力。但是,我想我会这样做(稍微干净一点):

if (($decoded = json_decode($data)) && !isset($decoded->type)) {
    $decoded->type = 'vehicle';
    $data = json_encode($decoded);
}

至少我觉得比较靠谱。希望对您有所帮助!