Jackson 2
Tue, May 4, 2021
4-minute read
1. dependency : jackson-databind
2. entity object class
@Data
public class Employer {
private String name;
private Integer age;
private String[] hobbies;
private List<String> friends;
private Map<String, BigDecimal> salary;
//initial an object
public static Employer getInstance(){
Employer employer = new Employer();
employer.setName("AA");
employer.setAge(45);
employer.setHobbies(new String[]{"XXXX", "YYYY"});
Map<String, BigDecimal> salary = new HashMap<String, BigDecimal>() {{
put("2000", new BigDecimal(10000000));
put("2010", new BigDecimal(62000000));
put("2020", new BigDecimal(112400000));
}};
playerStar.setSalary(salary);
playerStar.setFriends(Arrays.asList("BB", "CC", "DDs"));
return employer;
}
}
3. serialize
- writeValue
- writeValueAsString
- writerWithDefaultPrettyPrinter
@Test
void testObject2JSON() throws IOException {
//get an object
Employer em1 = Employer.getInstance();
//ObjectMapper is tool
ObjectMapper mapper = new ObjectMapper();
//1. serialize the employer object,store the result
mapper.writeValue(new File("d:\data\jackson\employer.json"), em1);
//2. return a string object
String jsonString = mapper.writeValueAsString(em1);
System.out.println(jsonString);
//3. return a string object with prettyprinter
String jsonInString2 = mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(em1);
System.out.println(jsonInString2);
}
4. deserialize
@Test
void testObject2JSON() throws IOException {
//ObjectMapper is tool
ObjectMapper mapper = new ObjectMapper();
// 1. read the JSON file, get java object
Employer em1 = mapper.readValue(new File("d:\data\jackson\employer.json"), Employer.class);
//2. read from JSON directly
String jsonString = "{\"name\":\"AA\",\"age\":45,\"hobbies\":[\"XXXX\",\"YYYY\"]}";
Employer em1 = mapper.readValue(jsonString, Employer.class);
System.out.println(em1);
}
5. @JsonProperty rename the object property
@Data
public class Employer {
@@JsonProperty("teamName")
private String name; // {"teamName": "AA"}
below code should be replaced with teamName
//2. read from JSON directly
String jsonString = "{\"name\":\"AA\",\"age\":45,\"hobbies\":[\"XXXX\",\"YYYY\"]}";
Employer em1 = mapper.readValue(jsonString, Employer.class);
6. @JsonInclude
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Employer {
// {"age": 45, "teamName" : "AA"}, null property would be ignored
7. get JSON data from URL
URL url = new URL("https://jsonplaceholder.typicode.com/posts/1");
ObjectMapper mapper = new ObjectMapper();
//2. read from JSON directly
Employer em1 = mapper.readValue(url, Employer.class);
8. @JsonCreator on constructor/static factory method
public class Employer {
private String name;
private Integer age;
private String[] hobbies;
private List<String> friends;
private Map<String, BigDecimal> salary;
//constructor
@JsonCreator
public Employer(@JsonProperty("name") String name,
@JsonProperty("age") Integer age,
@JsonProperty("hobbies") String[] hobbies,
@JsonProperty("friends") List<String> friends,
@JsonProperty("salary") Map<String, BigDecimal> salary) {
this.name = name;
this.age = age;
this.hobbies = hobbies;
this.friends = friends;
this.salary = salary;
}
}
}
public class Employer {
private String name;
private Integer age;
private String[] hobbies;
private List<String> friends;
private Map<String, BigDecimal> salary;
//constructor
@JsonCreator
public static Employer createEmployer(@JsonProperty("name") String name,
@JsonProperty("age") Integer age,
@JsonProperty("hobbies") String[] hobbies,
@JsonProperty("friends") List<String> friends,
@JsonProperty("salary") Map<String, BigDecimal> salary) {
Employer emp = new Employer();
emp.name = name;
emp.age = age;
emp.hobbies = hobbies;
emp.friends = friends;
emp.salary = salary;
return emp;
}
}
}
9. @ConstructorProperties is also used for deserialize
public class Employer {
private String name;
private Integer age;
private String[] hobbies;
private List<String> friends;
private Map<String, BigDecimal> salary;
@ConstructorProperties({"name", "age","hobbies" , "friends", "salary"})
public Employer(String name,
Integer age,
String[] hobbies,
List<String> friends,
Map<String, BigDecimal> salary) {
this.name = name;
this.age = age;
this.hobbies = hobbies;
this.friends = friends;
this.salary = salary;
}
}
}
10. LocalDateTime
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
private LocalDateTime birthDate;
11. exercise
{
"name":"AA",
"place":"BB",
"birthDate":"CC",
"departments": [{
"name":"department",
"local_place":"XXXX",
"pm":"jack"
}, {
"name":"test",
"local_place":"YYYY",
"pm":"mike"
}]
}
{
"name":"AA",
"place":"BB",
"birthDate":"CC",
"departments": [{
"name":"department",
"local_place":"XXXX",
"pm":"jack"
"employee_number":2000,
"product" : "ii"
}, {
"name":"test",
"local_place":"YYYY",
"pm":"mike",
"employee_number":2000,
"product" : "ii"
}]
}
public class Company {
private String name;
@JsonProperty("HQ")
private String headquarters;
private Department[] departments;
@JsonIgnore
private Date birthDate;
@JsonCreator
public Company(@JsonProperty("name") String name) {
this.name = name;
}
}
public class Department {
private String name;
private String pm;
private Map<String, Object> others = new HashMap<>();
@JsonCreator
public Department(@JsonProperty("name") String name) {
this.name = name;
}
@JsonProperty("projectManager")
public String getPm() {
return pm;
}
@JsonAnyGetter // get all undefined json in department
public Map<String, Object> any() {
return others;
}
@JsonAnySetter
public void set(String key, Object value) {
others.put(key, value);
}
}
Deserialization
public class Deserialization {
public static void main(String[] args) throws Exception {
//ObjectMapper is tool
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
Company company = mapper.readValue(new File("d:\data\jackson\employer.json"), Company.class);
System.out.print(company.getName());
System.out.print(company.getHeadquarters());
System.out.print(company.getBirthDate()); // null
Department[] departments = company.getDepartments();
for (Departments department : departments) {
System.out.print(department.getName());
System.out.print(department.getPm());
System.out.print(department.get("employee_number"));
System.out.print(department.get("product"));
}
}
}