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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With