Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Serde interface: deserialize to specific subtype #2852

Closed
eedijs opened this issue Dec 12, 2022 · 1 comment · Fixed by #2881
Closed

Serde interface: deserialize to specific subtype #2852

eedijs opened this issue Dec 12, 2022 · 1 comment · Fixed by #2881

Comments

@eedijs
Copy link

eedijs commented Dec 12, 2022

Current Behavior

Currently, when implementing the Serde interface, it's not possible to check the class of the deserializable value (for example - an enum class) to deserialize the value to that specific class, because in CoerceUtil class the register(Class<T> targetType, Serde<S, T> serde) method doesn't pass the class to serde.deserialize:

    public static <S, T> void register(Class<T> targetType, Serde<S, T> serde) {
        initializeCurrentClassLoaderIfNecessary();

        SERDES.put(targetType, serde);
        ConvertUtils.register(new Converter() {

            @Override
            public <T> T convert(Class<T> aClass, Object o) {
                return (T) serde.deserialize((S) o);
               // here we could pass the class as well - return (T) serde.deserialize(aClass, (S) o);
            }

        }, targetType);
    }

If the class is also passed to the serde.deserialize method, maybe the Serde interface could have another deserializeWithType (or similar) method instead?

Here's an example @ElideTypeConverter annotated class that could be used to deserialize enum classes that extend or implement a BaseEnum class:

@ElideTypeConverter(name = "BaseEnumSerde", type = Enum.class, subTypes = {
        EnumOne.class,
        EnumTwo.class,
        EnumThree.class
        // etc.
})
public class BaseEnumSerde implements Serde<String, BaseEnum> {

    @Override
    public BaseEnum deserialize(Class<? extends BaseEnum> clazz, String value) {
        return Arrays.stream(clazz.getEnumConstants())
                .filter(enumConstant -> enumConstant.getValue().equals(value))
                .findFirst().orElse(null);
    }

    @Override
    public String serialize(BaseEnum baseEnum) {
        return baseEnum.getValue();
    }
}

Your Environment

  • Elide version used: 6.1.9
@aklish
Copy link
Member

aklish commented Jan 29, 2023

Seems like something we can add before we finalize Elide 7.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants