1 | package testcode;
|
---|
2 |
|
---|
3 | import java.util.Objects;
|
---|
4 |
|
---|
5 | import com.fasterxml.jackson.annotation.JsonAutoDetect;
|
---|
6 | import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
|
---|
7 | import com.fasterxml.jackson.annotation.JsonCreator;
|
---|
8 | import com.fasterxml.jackson.annotation.JsonProperty;
|
---|
9 | import com.fasterxml.jackson.annotation.JsonTypeInfo;
|
---|
10 | import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
|
---|
11 | import com.fasterxml.jackson.core.JsonProcessingException;
|
---|
12 | import com.fasterxml.jackson.databind.ObjectMapper;
|
---|
13 |
|
---|
14 | /**
|
---|
15 | * jackson-serializable Person, also with extra age field and equals and
|
---|
16 | * hashcode
|
---|
17 | */
|
---|
18 | @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = As.WRAPPER_OBJECT)
|
---|
19 | @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
|
---|
20 | public class PersonJson {
|
---|
21 | private static final ObjectMapper jackson = new ObjectMapper();
|
---|
22 | private static final String serialized = "{\"PersonJson\":{\"name\":\"Kees\",\"age\":25}}";
|
---|
23 |
|
---|
24 | private final String name;
|
---|
25 | private Integer age;
|
---|
26 |
|
---|
27 | @JsonCreator
|
---|
28 | public PersonJson(@JsonProperty("name") String name,
|
---|
29 | @JsonProperty("age") Integer age) {
|
---|
30 | this.name = name;
|
---|
31 | this.age = age;
|
---|
32 | }
|
---|
33 |
|
---|
34 | @Override
|
---|
35 | public String toString() {
|
---|
36 | return "Person[" + name + "," + age + "]";
|
---|
37 | }
|
---|
38 |
|
---|
39 | @Override
|
---|
40 | public int hashCode() {
|
---|
41 | return Objects.hash(age, name);
|
---|
42 | }
|
---|
43 |
|
---|
44 | @Override
|
---|
45 | public boolean equals(Object obj) {
|
---|
46 | if (this == obj)
|
---|
47 | return true;
|
---|
48 | if (obj == null)
|
---|
49 | return false;
|
---|
50 | if (getClass() != obj.getClass())
|
---|
51 | return false;
|
---|
52 | PersonJson other = (PersonJson) obj;
|
---|
53 | return Objects.equals(age, other.age)
|
---|
54 | && Objects.equals(name, other.name);
|
---|
55 | }
|
---|
56 |
|
---|
57 | static public void main(String[] args) throws JsonProcessingException {
|
---|
58 | PersonJson person = new PersonJson("Kees", 25);
|
---|
59 | System.out.println(person.toString());
|
---|
60 | System.out.println(jackson.writeValueAsString(person));
|
---|
61 | System.out.println(
|
---|
62 | person.equals(jackson.readValue(serialized, PersonJson.class)));
|
---|
63 | /*-
|
---|
64 | Person[Kees,25]
|
---|
65 | {"PersonJson":{"name":"Kees","age":25}}
|
---|
66 | true
|
---|
67 | */
|
---|
68 | }
|
---|
69 | }
|
---|