【发布时间】:2019-02-07 10:01:17
【问题描述】:
我需要将 Map 转换为 POJO。我参考了下面的链接,对于简单的键(employeeId,firstName,lastName)它工作正常。
对于关联(有线)密钥(department.departmentId,department.departmentName)它不起作用
Convert a Map<String, String> to a POJO
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;
}
地图的键和值是字符串,我是从其他函数中获得的。会有多个嵌套的属性键,例如 department.departmentId 或 地址.addressId
【问题讨论】:
-
运行时,在线程“main”java.lang.IllegalArgumentException 中出现此错误异常:无法识别的字段“department.departmentId”