简体   繁体   中英

Is it possible to change value when using ConstraintValidator in Spring Boot?

I have a string field that may contain whitespaces at leading and trailing. I want to trim these whitespaces and return trimmed text using ConstraintValidator . If the text is null, I want to return null.

When looking at the implementation examples as shown on this link, I am not sure how can I create a method that gets string and return string instead of isValid() method. So, how can I implement this approach based on the given scenario?

Use jackson JsonDeserialize annotation to do this.

Example:

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;

import java.io.IOException;

public class TrimWhiteSpace extends StdDeserializer<String> {

  private static final long serialVersionUID = -4993230470571124275L;

  public TrimWhiteSpace() {
    this(null);
  }

  protected TrimWhiteSpace(final Class<?> vc) {
    super(vc);
  }

  @Override
  public String deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
    return p.getText() == null ? null : p.getText().trim();
  }
}

You can use this annotation as below:

public class Request {

    @JsonDeserialize(using = TrimWhiteSpace.class)
    private String name;

}

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