Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Resolve to custom type with Symfony serializer

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

Thanks in advance!

(btw, I’m not using the Symfony framework, just the Serializer component. I do use the Laravel framework).

>Solution :

I would suggest creating a custom normalizer. See https://symfony.com/doc/current/serializer/custom_normalizer.html

Put a mapping array into this normalizer which maps the different "type" values to their corresponding class names. You can then use this information to normalize the data into an object of the desired class.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading