Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jms serializer bundle serialize super class

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?

like image 545
Charlie Lucas Avatar asked Mar 03 '26 02:03

Charlie Lucas


1 Answers

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!

like image 144
Javier C. H. Avatar answered Mar 04 '26 20:03

Javier C. H.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!