我需要将地图转换为POJO。我参考了下面的链接,对于简单的键(雇员ID、firstName、lastName),它可以正常工作。
对于关联的(有线)密钥(departmentId、departmentName),它不起作用
转换地图
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Employee {
private int employeeId;
private String firstName;
private String lastName;
private Department department;
public static void main(String[] args) {
Map<String,String> input = constructMap();
final ObjectMapper mapper = new ObjectMapper();
//mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
final Employee employee = mapper.convertValue(input, Employee.class);
System.out.println(employee);
}
private static Map<String,String> constructMap() {
Map<String,String> obj = new HashMap<String,String>();
obj.put("employeeId","1");
obj.put("firstName","firstName");
obj.put("lastName","lastName");
//obj.put("department.departmentId","123");
//obj.put("department.departmentName","Physics");
return obj;
}
} // Employee class end
public class Department {
private int departmentId;
private String departmentName;
}
映射的键和值是字符串,我从其他函数中获取。会有多个嵌套的属性键,如departmentId或addressId. addressId
您不需要使用部门.部门ID
和部门.部门名称
。相反,您必须在您的部门. class
上调用第二个转换值
。之后,您可以将创建的部门
设置为您的员工
。
主要
public static void main(String[] args)
{
Map<String,Object> input = constructMap();
ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Employee employee = mapper.convertValue(input, Employee.class);
Department department = mapper.convertValue(input, Department.class);
employee.setDepartment(department);
System.out.println(employee);
}
private static Map<String, Object> constructMap()
{
Map<String, Object> obj = new HashMap<>();
obj.put("employeeId", "1");
obj.put("firstName", "firstName");
obj.put("lastName", "lastName");
obj.put("departmentId", "123");
obj.put("departmentName", "Physics");
return obj;
}
员工
public class Employee
{
private int employeeId;
private String firstName;
private String lastName;
private Department department;
public int getEmployeeId()
{
return employeeId;
}
public void setEmployeeId(int employeeId)
{
this.employeeId = employeeId;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public Department getDepartment()
{
return department;
}
public void setDepartment(Department department)
{
this.department = department;
}
}
部
public class Department
{
private int departmentId;
private String departmentName;
public int getDepartmentId()
{
return departmentId;
}
public void setDepartmentId(int departmentId)
{
this.departmentId = departmentId;
}
public String getDepartmentName()
{
return departmentName;
}
public void setDepartmentName(String departmentName)
{
this.departmentName = departmentName;
}
}