我想从POJO那里得到一个json。我只想在设置器上获取Json(为了设置对象的集合)。
我有一个公司类,其中包含一组员工。 当我在公司对象上设置employee的集合时,我期望看到ObjectMapper生成的Json对象上的集合。但它没有用。
这里是我的代码和问题
@Entity
public class Company implements Serializable {
//-------------------
// PROPERTY
//-------------------
@ManyToMany
@JsonIgnore
@JoinTable(name = "COMPANY_EMPLOYEE",
joinColumns = @JoinColumn(name="company_id", referencedColumnName="ID"),
inverseJoinColumns = @JoinColumn(name="employees_id", referencedColumnName="ID"))
private Set<Employee> employees = new HashSet<>();
//-------------------
// GETTER AND SETTER
//-------------------
@JsonIgnore
public Set<Employee> getEmployees() {
return employees;
}
@JsonProperty
public void setEmployees(Set<Employee> employees) {
this.employees = employees;
}
}
//------ In Main Application
Company company = new Company();
company.setName("Company");
//etc....... company properties
Employee employee = new Employee();
employee.setFirstName("FirstName");
//etc....... employee properties
//Create the set of employee
Set<Employee> employeeSet = new HashSet<>();
employeeSet.add(employee);
//Add the list/set of employee to the company
company.setEmployees(employeeSet);
//Expect to have the employee set here but it's empty...
ObjectMapper objectMapper = new ObjectMapper();
System.out.println(new String(objectMapper.writeValueAsBytes(company)));
更新
我按照这篇文章解释了async mechanism of JsonIgnore with JsonProperty。 (这正是我想要的)
提前致谢。