Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize enum with @JsonCreator using a factory method

I'm trying to de-serialize a json to an enum using jackson. If the factory method has just one argument, it works fine. As soon as we add more arguments it stops working.

here is the code example that I tried.

public enum Test {
    FIRST(1, "first");

    private final int intProp;
    private final String stringProp;

    Test(int i, String stringProp) {
        this.stringProp = stringProp;
        this.intProp = i;
    }

    private static final Map<String, Test> allEntries = new HashMap<>(Test.values().length);
    static {
        for(Test each : Test.values()){
            allEntries.put(getCode(each.intProp, each.stringProp), each);
        }
    }

    private static String getCode(int i, String s){
        return s + i;
    }

    @JsonCreator(mode = Mode.PROPERTIES)
    public static Test forValues(@JsonProperty("intProp") int intProp,
                                 @JsonProperty("stringProp") String stringProp
                                 ){
        return allEntries.get(getCode(intProp,stringProp));
    }
}

using the following code to deserialize the json

String json = "{\"intProp\":1,\"stringProp\":\"first\"}";
ObjectMapper mapper = new ObjectMapper();

Test enumValue = mapper.readValue(json, Test.class); //fails 

This is the exception that I'm getting

com.fasterxml.jackson.databind.JsonMappingException: Unsuitable method

Versions : jackson-databind 2.5.1, jackson-annotations 2.5.0

I don't want to write a custom deserializer, is there a mistake in my approach or the option is just not supported by jackson ?

Also the same thing works when using a class instead of enum.

like image 744
Prateek Avatar asked Sep 12 '15 11:09

Prateek


1 Answers

It looks like this feature is actually missing in the jackson library. I have opened an issue in jackson-databind github project. Will have to wait for them to fix it in some upcoming release.

like image 196
Prateek Avatar answered Nov 15 '22 00:11

Prateek