SuperBob
SuperBob

Reputation: 86

Equivalance symfony/serializer "SerializedPath" for jms/serializer

I have this particular json to decode with jms/serializer:

{
  "id": 42,
  "attributes": {
    "name": "toto",
    "alternativeText": null
  }
}

into:

class Image {
  public string $name;
}

With symfony/serializer a can use the attribute SerializedPath

#[SerializedPath('[attributes][name]')]
public string $name;

Did an equivalence exist for jms/serializer ?

Upvotes: 1

Views: 481

Answers (1)

SuperBob
SuperBob

Reputation: 86

I found a little workaround, a use the event serializer.pre_deserialize to transform the data before the serialisation:

class ImageSubscriber implements EventSubscriberInterface
{

    public static function getSubscribedEvents()
    {
        return [
            [
                'event' => 'serializer.pre_deserialize',
                'method' => 'onPreSerialize',
                'class' => Image::class,
                'format' => 'json',
                'priority' => 0,
            ]
        ];
    }

    public function onPreSerialize(PreDeserializeEvent $event)
    {
        $data = $event->getData();
        $data['name'] = $data['attributes']['name'];

        $event->setData($data);
    }
}

Upvotes: 0

Related Questions