I have a JSON object something like this:
{
"things": [
{"type":"custom"},
{"type":"another"}
]
}
I'm using the Symfony Serializer component to serialize that JSON data into PHP objects (or classes).
Right now I have this:
class Company {
private array $things = [];
public function setThings(array $thing): void {
$this->things = $thing;
}
public function addThing(Thing $thing): void {
$this->things[] = $thing;
}
public function getThings(): array {
return $this->things;
}
}
class Thing {
public string $type;
}
$serializer = new Serializer(
[
new ArrayDenormalizer(),
new ObjectNormalizer(null, null, null, new ReflectionExtractor()),
],
[new JsonEncoder()],
);
$deserialized = $serializer->deserialize($json, Company::class, 'json');
This correctly serializes the JSON data into a Company
instance with 2 instances of the Thing
class but I'd like to use a custom thing
class based on the type property.
{"type": "custom"} should return an instance of CustomType (extends Type of course)
{"type": "another"} should return an instance of Another (extends Type of course)
How do I handle this?
(btw, I'm not using the Symfony framework, just the Serializer component. I do use the Laravel framework).