package testcode; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeInfo.As; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; /** * jackson-serializable Person, also with extra age field and equals and * hashcode */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = As.WRAPPER_OBJECT) @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) public class PersonJson { private static final ObjectMapper jackson = new ObjectMapper(); private static final String serialized = "{\"PersonJson\":{\"name\":\"Kees\",\"age\":25}}"; private final String name; private Integer age; @JsonCreator public PersonJson(@JsonProperty("name") String name, @JsonProperty("age") Integer age) { this.name = name; this.age = age; } @Override public String toString() { return "Person[" + name + "," + age + "]"; } @Override public int hashCode() { return Objects.hash(age, name); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PersonJson other = (PersonJson) obj; return Objects.equals(age, other.age) && Objects.equals(name, other.name); } static public void main(String[] args) throws JsonProcessingException { PersonJson person = new PersonJson("Kees", 25); System.out.println(person.toString()); System.out.println(jackson.writeValueAsString(person)); System.out.println( person.equals(jackson.readValue(serialized, PersonJson.class))); /*- Person[Kees,25] {"PersonJson":{"name":"Kees","age":25}} true */ } }