Skip to content

Instantly share code, notes, and snippets.

@codecitizen
Created February 24, 2020 11:56
Show Gist options
  • Select an option

  • Save codecitizen/fdad048a8750b987339bfbf7f5f2edb6 to your computer and use it in GitHub Desktop.

Select an option

Save codecitizen/fdad048a8750b987339bfbf7f5f2edb6 to your computer and use it in GitHub Desktop.

Revisions

  1. codecitizen created this gist Feb 24, 2020.
    63 changes: 63 additions & 0 deletions ValidjacksonspringApplication.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,63 @@
    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 + '\'' +
    '}';
    }
    }

    }