简体   繁体   中英

stripping whitespace when deserializing JSON using Jackson

I have a Dropwizard application with a bunch of APIs which are published. I need to strip trailing/leading whitespaces as well as carriage returns, tabs, etc. from incoming string values (such as address, names). Rather than going and changing each API implementation and doing so manually, I thought about configuring a JSON deserializer to do so.

I can't seem to find such an option in Jackson. Also, even if I create a custom deserializer and find how to register it within the Dropwizard application, it seems that each deserializer is configured per specific class rather than "global".

My question is whether there is an option in Jackson to configure a GLOBAL deserializer for any java.lang.String property (simple or part of another object) or some sort of global callback method which will allow me to examine and potentially modify a JSON property value.

I found a solution. By implementing a custom JsonDeserializer, you can manipulate values.

public class WhitespaceDeserializer extends JsonDeserializer<String> {
    @Override
        public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        return p.getText().trim();
}

The deserializer then has to be registered with the object mapper:

ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule().addDeserializer(String.class, new WhitespaceDeserializer());
mapper.registerModule(simpleModule);

A little bit more work than I thought - I was hoping there is a simple an existing way of setting a flag somewhere, but this does the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM