Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

java - Prevent automatic String to Integer conversion in 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...