5

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.

Krzysztof Krasoń
  • 26,515
  • 16
  • 89
  • 115

1 Answers1

5

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"])
Krzysztof Krasoń
  • 26,515
  • 16
  • 89
  • 115
varren
  • 14,551
  • 2
  • 41
  • 72
  • 2
    Note that there's a bug whereby this feature is ignored if you've enabled afterburner: https://github.com/FasterXML/jackson-modules-base/issues/69 – Dan Jan 09 '19 at 19:39