Skip to content

Instantly share code, notes, and snippets.

@codecitizen
Created February 24, 2020 11:56
Show Gist options
  • Save codecitizen/fdad048a8750b987339bfbf7f5f2edb6 to your computer and use it in GitHub Desktop.
Save codecitizen/fdad048a8750b987339bfbf7f5f2edb6 to your computer and use it in GitHub Desktop.
Example of using the `@Size` Annotation with Spring and Jackson.
package com.docutools.demo.validjacksonspring;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import javax.validation.constraints.Size;
import java.util.Objects;
@RestController
@SpringBootApplication
public class ValidjacksonspringApplication {
public static void main(String[] args) {
SpringApplication.run(ValidjacksonspringApplication.class, args);
}
@PostMapping(path = "/hello")
public String greet(@RequestBody @Valid Person person) {
return String.format("Hello %s", person.getName());
}
public static class Person {
@Size(max = 5, message = "A persons name must not be longer than 5 characters.")
private String name;
@JsonCreator
public Person(@JsonProperty(value = "name", required = true) String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
'}';
}
}
}
@Rahman2001
Copy link

Rahman2001 commented Dec 28, 2021

Thanks for such a good explanation of @ Size. But, if you don't mind, could you comment what @ JsonCreator and @ JsonProperty does exactly in this code or in general ?
Thanks in advance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment