Search code examples
javajsonjacksonjackson2

How to disable conversion of 0/1 to true/false in jackson 2.9.x


I have a project that needs a strict json policy.

Example:

public class Foo {
    private boolean test;

    ... setters/getters ...
}

Following json should work:

{
    test: true
}

And following should fail (throw exception):

{
    test: 1
}

same for:

{
    test: "1"
}

Basically I want the deserialization to fail if someone provides something different than true or false. Unfortunately jackson treats 1 as true and 0 as false. I couldn't find a deserialization feature that disables that strange behavior.


Solution

  • Can disable MapperFeature.ALLOW_COERCION_OF_SCALARS From docs

    Feature that determines whether coercions from secondary representations are allowed for simple non-textual scalar types: numbers and booleans.

    If you also want it to work for null, enable DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES (More Info)

    ObjectMapper mapper = new ObjectMapper();
    
    //prevent any type as boolean
    mapper.disable(MapperFeature.ALLOW_COERCION_OF_SCALARS);
    
    // prevent null as false 
    // mapper.enable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES);
    
    System.out.println(mapper.readValue("{\"test\": true}", Foo.class));
    System.out.println(mapper.readValue( "{\"test\": 1}", Foo.class));
    

    Result:

     Foo{test=true} 
    
     Exception in thread "main"
     com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot
     coerce Number (1) for type `boolean` (enable
     `MapperFeature.ALLOW_COERCION_OF_SCALARS` to allow)  at [Source:
     (String)"{"test": 1}"; line: 1, column: 10] (through reference chain:
     Main2$Foo["test"])