I use jms serializer bundle to serialize a super class but i want to serialize my super class like this:
/**
* @Discriminator(field = "type", map = {"vehicle": "Vehicle", "car": "Car", "moped": "Moped"})
*/
class Vehicle { }
class Car extends Vehicle { }
class Moped extends Vehicle { }
but it doesn't work i can get fied 'type' in my json for children but not for my superclass Vehicle. For instant i use an hack:
$data = $this->serializer->serialize($vehicle, 'json');
if(!strpos(",\"type\":", $data))
{
$data = substr_replace($data ,",\"type\":\"vehicle\"}",-1);
}
to add my field and can deserialize my object after.
Have you any cleaner idea for this?
As per the documentation:
@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.
So I'm afraid there's nothing much you can do about it. However, I think I would do it like this (somewhat slightly cleaner):
if (($decoded = json_decode($data)) && !isset($decoded->type)) {
$decoded->type = 'vehicle';
$data = json_encode($decoded);
}
At least is more reliable I think. I hope it helps!