schmittjoh / serializer

Library for (de-)serializing data of any complexity (supports JSON, and XML)
http://jmsyst.com/libs/serializer
MIT License
2.32k stars 588 forks source link

Feature request: Allow literal discriminator values #1532

Closed mwolff-fn closed 8 months ago

mwolff-fn commented 9 months ago
Q A
Bug report? no
Feature request? yes
BC Break report? no
RFC? no

When I want to deserialize some JSON into a class which contains child object that have an abstract class or interface as a typehint, I need to set the Discriminator annotation for the abstract class, providing a map that associates the value of a given property with the concrete class name, like so:

#[Serializer\Discriminator(
    field: "__type__",
    map: [
        Email::class => Email::class,
        Fax::class => Fax::class,
        Mobile::class => Mobile::class,
        Phone::class => Phone::class,
    ],
)]
abstract class AbstractContactData implements ContactDataInterface
{
    // ...
}

As you can see, in my case, the property "type" in the JSON data already contains the fully qualified name of the concrete class. Yet, I still have to define the map array in the Discriminator annoation - otherwise, it would throw an error ("InvalidMetadataException: The discriminator map cannot be empty").

This seems very redundant. Would you consider a feature like passing "map: false" or "literal: true" to disable manual mapping and using the value of the given property as the literal class name?

scyzoryck commented 8 months ago

Hi! Thanks for feedback. I believe that exposing FQN in APIs are not popular practice in the APIs. Looking at the implementation it would require a lot of changes in the serialiser as there is no easy way to fetch child class names. I do not think that adding such feature would be possible at this point.

Best, Marcin.

mwolff-fn commented 8 months ago

Ok, thanks for looking into it anyway :-)