jackson-databind icon indicating copy to clipboard operation
jackson-databind copied to clipboard

How could I stop converting Number or Boolean to String ?

Open sonikjunior opened this issue 2 years ago • 3 comments

My JSON includes list of strings:

{
  "recipients": [
    "string1",
    "string2",
    "string3"
  ],
  "sendToSupport": true
}

And if someone send Number or Boolean type inside List :

{
  "recipients": [
    1,
    2,
    true
  ],
  "sendToSupport": true
}

Jackson deserializes it all to String like this:

{
  "recipients": [
    "1",
    "2",
    "true"
  ],
  "sendToSupport": true
}

Could you explain how to stop this ? I want to throw 400 if the types don't fit

sonikjunior avatar Dec 03 '21 12:12 sonikjunior

I solved it using:

public class CustomStringDeserializer extends JsonDeserializer<String> {

    @Override
    public String deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException {
        if (Set.of(VALUE_NUMBER_INT, VALUE_NUMBER_FLOAT, VALUE_FALSE, VALUE_TRUE).contains(jsonParser.getCurrentToken())) {
            throw new IllegalArgumentException();
        }
        return jsonParser.getValueAsString();
    }
}

and config:

@Configuration
public class CommonConfiguration {

    @Bean
    public ObjectMapper objectMapper() {
        SimpleModule module = new SimpleModule();
        module.addDeserializer(String.class, new CustomStringDeserializer());

        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(module);
        return mapper;
    }
}

But it would be great to have something like this:

       ObjectMapper mapper = new ObjectMapper();
        mapper.disable(MapperFeature.ALLOW_CAST_INTS_TO_STRING);
        mapper.disable(MapperFeature.ALLOW_CAST_BOOLEANS_TO_STRING)

sonikjunior avatar Dec 21 '21 13:12 sonikjunior

have you tried the coercion config?

yawkat avatar Dec 29 '21 08:12 yawkat

+1 for CoercionConfig, explained f.ex here:

https://cowtowncoder.medium.com/jackson-2-12-most-wanted-4-5-cbc91c00bcd2

Note: while the central system for configuring thing is complete, each individual JsonDeserializer implementation has to make use of it so support for actual configuration changes has some gaps but is slowly increasing over new versions. If specific coercion configuration does not seem to be blocking things please file a new issue.

cowtowncoder avatar Dec 31 '21 22:12 cowtowncoder