Jackson reads input numbers as Strings. As an example below Student class read name 4567 as a String.
ex: input
{
name: 4567
...
}
Java class
Class Student {
String name;
...
}
Jackson is parsing the JSON text and mapping the number value to the string field, and I don't want the type conversion, i.e. for the number to be converted to a string. In this scenario Jackson converts the value from int (4567) to String("4567"). How this behavior can changes to throw an exception if other type provided to fail ?
Custom deserializer registered for java.lang.String should definitely work and let you prevent conversion. Deserializers will directly see content via JsonParser so they can detect underlying token type.
This will help you:
public class ForceStringDeserializer extends JsonDeserializer<String> {
@Override
public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
if (jsonParser.getCurrentToken() == JsonToken.VALUE_NUMBER_INT) {
throw deserializationContext.wrongTokenException(jsonParser, JsonToken.VALUE_STRING, "Attempted to parse int to string but this is forbidden");
}
return jsonParser.getValueAsString();
}
}
You can find more info here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With