4

I found an answer similar to this question but it isn't working when posting JSON data. I have the following:

@ControllerAdvice
public class ControllerConfig {

    @InitBinder
    public void initBinder ( WebDataBinder binder ) {
        StringTrimmerEditor stringtrimmer = new StringTrimmerEditor(true);
        binder.registerCustomEditor(String.class, stringtrimmer);
    }
}

I know that the code is being reached during binding via debugging but when I pass in data like:

{ "companyId": "    ABC     "}

ABC isn't actually being trimmed during binding. My guess is that this only works with request params and not raw JSON bodies but not sure about that. If that is the case, is there something I can do that is similar?

Community
  • 1
  • 1
Gregg
  • 34,973
  • 19
  • 109
  • 214

2 Answers2

2

Create this JsonDeserializer

public class WhiteSpaceRemovalDeserializer extends JsonDeserializer<String> {
     @Override
     public String deserialize(JsonParser jp, DeserializationContext ctxt) {
         // This is where you can deserialize your value the way you want.
         // Don't know if the following expression is correct, this is just an idea.
         return jp.getCurrentToken().asText().trim();
     }
 }

and set this to your property

@JsonDeserialize(using=WhiteSpaceRemovalSerializer.class)
 public void setAString(String aString) {
    // body
 }
ali akbar azizkhani
  • 2,213
  • 5
  • 31
  • 48
-1

Try this, Create a class. Annotate the class with @JsonComponent extend the JsonDeserializer and, add your trimming logic in the overridden method,

this will automatically trim the whitespaces in the json request, when it hits the controller, no external properties needed to activate this.

@JsonComponent
public class WhiteSpaceRemover extends JsonDeserializer<String> {

  @Override
  public String deserialize(JsonParser arg0, DeserializationContext arg1)
        throws IOException, JsonProcessingException {
    return arg0.getValueAsString().trim();
  }
}