2

I have spring application which expose REST endpoint, lets name it "doAction". As the request it consumes object:

class Person{
private String name;
private String email;
}

Some clients can call this endpoint by passing data with different practice of writing words, like:

Peter_1
name = Peter 
email = peter@gmail.com  (lower case)

Mark_2
name = mark
email = MARK@gmail.com (upper case)

Julia_3
name = julia
email = JuliaToward@gmail.com (camel case)

Is there some approach to force all income data be parsed to lowercase(lets assume all fields are Strings)?

So as a result I desire to have:

Peter_1
name = peter 
email = peter@gmail.com

Mark_2
name = mark
email = mark@gmail.com

Julia_3
name = julia
email = juliatoward@gmail.com

Solution for Jackson is appreciated.

Speise
  • 789
  • 1
  • 12
  • 28

2 Answers2

1

Short answer Call toLower in the setter

Here is an example:

class Animal
{
    private String name;

    public void setName(final String newValue)
    {
        StringUtils.trimToNull(StringUtils.lowerCase(newValue));
    }
}

I also recommend either trimToNUll or trimToEmpty.

DwB
  • 37,124
  • 11
  • 56
  • 82
0

If you are using Spring Data Rest with spring mvc and you want all incoming string data to be in lower case then define following

public class StringSerializer extends StdDeserializer<String>{

    public StringSerializer() {
        this(null);
    }

    public StringSerializer(Class<String> vc) {
        super(vc);
    }

    @Override
    public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        JsonToken t = p.getCurrentToken();
        if (t==JsonToken.VALUE_STRING){
            String receivedValue = p.getText();
            if (receivedValue == null)
                return null;
            else
                return receivedValue.toLowerCase();
        }else{
            return null;
        }   
    }

}

And following:

@Configuration
public class RestDataConfig  extends RepositoryRestMvcConfiguration {

    @Override
    @Bean
    public ObjectMapper halObjectMapper() {

        ObjectMapper mapper = super.halObjectMapper();
        SimpleModule module = new SimpleModule();
        module.addDeserializer(String.class, new StringSerializer());
        mapper.registerModule(module);
        return mapper;
    }
}
ArslanAnjum
  • 1,674
  • 2
  • 17
  • 31