0

I have a symfony serializer that i initialize this way :

$this->serializer = new Serializer(
    [
        new ArrayDenormalizer(),
        new UidNormalizer(),
        new BackedEnumNormalizer(),
        new DateTimeNormalizer(),
        new ObjectNormalizer(
            classMetadataFactory: new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader())),
            nameConverter: new CamelCaseToSnakeCaseNameConverter(),
            propertyTypeExtractor: new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()])
        ),
    ],
    [new JsonEncoder()]
);

and a method on my object, i want to serialize with a specific name (getRrule being an existant method so i can't just rename it)

#[Serializer\Groups(['prestation:default'])]
#[Serializer\SerializedName('rrule')]
public function getRruleRfcString(): ?string
{
    return $this->rrule?->rfcString();
}

but when serialized i get : "rrule_rfc_string" => null

instead of : "rrule" => null

also the serialization group is working fine so i dont know why only one attribute out of two are working...

Methraen
  • 11
  • 3

1 Answers1

1

I just resolved it:

$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$this->serializer     = new Serializer(
    [
        new ArrayDenormalizer(),
        new UidNormalizer(),
        new BackedEnumNormalizer(),
        new DateTimeNormalizer(),
        new ObjectNormalizer(
            classMetadataFactory: new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader())),
            nameConverter: new MetadataAwareNameConverter($classMetadataFactory, new CamelCaseToSnakeCaseNameConverter()),
            propertyTypeExtractor: new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()])
        ),
    ],
    [new JsonEncoder()]
);

just needed to add a MetadataAwareNameConverter plus put the CamelCaseToSnakeCaseNameConverter as fallback name converter

Methraen
  • 11
  • 3
  • Unless you are using the serializer as a standalone component please use it as described in https://symfony.com/doc/current/serializer.html#using-the-serializer-service. Symfony as a framework comes with a preconfigured out of the box serializer service you can inject which has all these things set up which avoids a lot of hassle. – Jenne Jun 06 '23 at 13:09