I've been struggling with an issue. My endpoint receives a lot of broken API calls from a PHP application where there are often false
booleans set for numerical fields.
How can I attach a custom deserializer to my ObjectMapper
that would convert all false
values to null
or 0
depending upon the type of the corresponding numerical property in the bean?
Here's the JSON:
{
"name": "My Name",
"image_url": null,
"price": false
"list_price": false;
}
Here's an example of the bean:
public class Item {
public String name;
public String imageUrl;
public Double price;
public double listPrice;
}
I've only a custom deserializer along the lines of this but this means that I explicitly need to attach this to every field:
public class FalseAsNullDeserializer extends JsonDeserializer<Object> implements ContextualDeserializer {
private final Class targetType;
private FalseAsNullDeserializer() {
this.targetType = null;
// required by Jackson
}
public FalseAsNullDeserializer(Class<?> targetType) {
this.targetType = targetType;
}
@Override
public Object deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException {
JsonNode node = parser.readValueAsTree();
if (!node.isObject() && !node.asBoolean()) {
return null;
} else {
return JSONUtils.getMapper().treeToValue(node, targetType);
}
}
@Override
public JsonDeserializer<?> createContextual(DeserializationContext context, BeanProperty property)
throws JsonMappingException {
return new FalseAsNullDeserializer(property.getType().getRawClass());
}
}