Created
February 24, 2020 11:56
-
-
Save codecitizen/fdad048a8750b987339bfbf7f5f2edb6 to your computer and use it in GitHub Desktop.
Example of using the `@Size` Annotation with Spring and Jackson.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 + '\'' + | |
'}'; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.