Skip to content

Enum as key of nested Map gets set as String when converting from string to Object #21

@charlie-harvey

Description

@charlie-harvey
public enum GreetingType {
    ENGLISH, CHINESE, HAWAIIAN;
}

public class Greeting {
    private String word;

    public void setWord(String word) {
        this.word = word;
    }

    public String getWord() {
        return word;
    }
}

public class MyObj {
    private Integer id;
    private Map<GreetingType, Greeting> greetings;

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getId() {
        return id;
    }

    public void setGreetings(Map<GreetingType, Greeting> greetings) {
        this.greetings = greetings;
    }

    public Map<GreetingType, Greeting> getGreetings() {
        return greetings;
    }
}

// DOES NOT WORK:
String json = "{\"id\": \"1\", \"greetings\": {\"ENGLISH\": {\"word\": \"hello\"} }, {\"CHINESE\": {\"word\": \"nihao\"} }, {\"HAWAIIAN\": {\"word\": \"aloha\"} } }";
MyObj myObj = JSON.std.beanFrom(MyObj.class, json);
// keys of map greetings map are strings - not enums
myObj.getGreetings().get(GreetingType.ENGLISH);  // -> Error
myObj.getGreetings().get("ENGLISH");  // -> Success

// DATABIND ObjectMapper WORKS AS EXPECTED:
ObjectMapper mapper = new ObjectMapper();
MyObj myObj = mapper.readValue(json, MyObj.class);
myObj.getGreetings().get(GreetingType.ENGLISH);  // -> Success

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions