-1

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).

yivi
  • 42,438
  • 18
  • 116
  • 138
frietkot
  • 891
  • 12
  • 28

1 Answers1

1

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.

René Pöpperl
  • 567
  • 5
  • 18