Showing posts with label SPRING. Show all posts
Showing posts with label SPRING. Show all posts

Tuesday, July 2, 2019

Remove leading and trailing spaces on Strings across your spring application with Jackson

If you are using Jackson to convert http messages, you can add a custom String Deserializer to removes heading and trailing spaces across you application in a few lines.

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;

public class StringDeserializer extends StdDeserializer<string> {

  private static final long serialVersionUID = 1623333240815834335L;

  public StringDeserializer() {
    this(null);
  }

  private StringDeserializer(Class vc) {
    super(vc);
  }

  @Override
  public String deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    String valueAsString = jp.getValueAsString();
    if (StringUtils.isEmpty(valueAsString)) {
      return null;
    }

    return valueAsString.trim();
  }
}
To activate it, add this bean to your WebConfig file.

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

  @Bean
  public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
    MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    jsonConverter.setObjectMapper(objectMapper);

    SimpleModule module = new SimpleModule();

    module.addDeserializer(String.class, new StringDeserializer());
    objectMapper.registerModule(module);

    return jsonConverter;
  }
}