Skip to content

Extended enum values are not handled as enums when used as Map keysΒ #2457

@ankulikov

Description

@ankulikov

Hello, guys!
I've faced with a problem of inconsistent enum serialization:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Map;

public class JacksonEnumTest {

    public static void main(String[] args) throws JsonProcessingException {
        final ObjectMapper mapper = new ObjectMapper();
        final Map<MyEnum, String> map = Map.of(
            MyEnum.A, "1",
            MyEnum.B, "2");
        System.out.println(mapper.writeValueAsString(map));
    }

    enum MyEnum {
        A,
        B() {
            @Override
            public void foo() {
                // also do nothing
            }
        }

        public void foo() {
            // do nothing
        }

        @Override
        public String toString() {
            return name() + " as string";
        }
    }
}

Expected result:

{"A":"1", "B":"2"}

Actial result:

{"A":"1", "B as string":"2"}

Research:

Actually B.getClass() is not MyEnum but MyEnum$1 which is not enum anymore!

MyEnum.B.getClass().isEnum() == false

So, my proposal is to add this check to com.fasterxml.jackson.databind.JavaType:

 @Override
    public final boolean isEnumType() { 
    return  _class.isEnum() || Enum.class.isAssignableFrom(_class);
 }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions