Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent automatic String to Integer conversion in Jackson

Tags:

java

json

jackson

I have a simple POJO:

public class ADate {
    private Integer day;
    private Integer month;
    private Integer year;
    ... // getters/setters/constructor
}

The following JSON Document gets deserialized correctly into ADate:

{ 
  "day":"10", 
  "month":"2", 
  "year":"1972"
}

Jackson converts the String into Integer automatically.

Is there a way to avoid this automatic conversion and have Jackson to fail if the Integer values are defined as String.

like image 396
Luciano Avatar asked Sep 20 '16 15:09

Luciano


2 Answers

There is a configuration setting on the ObjectMapper called the MapperFeature.ALLOW_COERCION_OF_SCALARS. If set to false, it will prevent ObjectMapper from coercing String representations of numbers and booleans into their Java counterparts. Only strict conversions will be allowed.

Exact usage example:

objectMapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false);

References:

[1] Add MapperFeature.ALLOW_COERCION_OF_SCALARS for enabling/disabling coercions #1106: https://github.com/FasterXML/jackson-databind/issues/1106

[2] Prevent coercion of int from empty String to null if DeserializationFeature .FAIL_ON_NULL_FOR_PRIMITIVES is true #1095: https://github.com/FasterXML/jackson-databind/issues/1095

[3] ALLOW_COERCION_OF_SCALARS http://fasterxml.github.io/jackson-databind/javadoc/2.9/

like image 123
sidmishraw Avatar answered Sep 19 '22 13:09

sidmishraw


I've found the some interesting code on Jackson github issues. Changed it a little and that's what I got:

public class ForceIntegerDeserializer extends JsonDeserializer<Integer> {

    @Override
    public int deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        if (jsonParser.getCurrentToken() != JsonToken.VALUE_NUMBER_INT) {
            throw deserializationContext.wrongTokenException(jsonParser, JsonToken.VALUE_STRING, "Attempted to parse String to int but this is forbidden");
        }
        return jsonParser.getValueAsInt();
    }
}
like image 33
xenteros Avatar answered Sep 18 '22 13:09

xenteros