有没有一种更简单的方法可以使用 Java 或 Jackson 在 Java 7 中转换 POJO 列表中的映射列表?

Is there a simpler way to convert a List of Maps in a List of POJO in Java 7 using Java or Jackson?

前奏:我正在使用带有 select 的 hibernate 3,return 只有一些指定的字段。我没有找到获取 POJO 列表的方法,我找到的最好方法是 return 使用 query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);

的地图列表

我有一个 Map<String, Object> 的列表。现在,我发现将其转换为 POJO 列表的方法是使用 Jackson:

ObjectMapper objectMapper = new ObjectMapper();
MyPojo myPojo;

List<myPojo> res = new ArrayList<>();

// rows is the List<Map<String, Object>>
for (Object row : rows) {
    myPojo = objectMapper.convertValue(row, MyPojo.class);
    res.add(myPojo);
}

有没有更简单的方法?

您可以使用 TypeReference:

ObjectMapper objectMapper = new ObjectMapper();
List<MyPojo> res = objectMapper.convertValue(rows, new TypeReference<MyPojo>() {});

你就在附近,Yann :-)

我找到了,感谢cowtowncoder:

TypeReference<List<MyPojo>> typeReference = new TypeReference<List<MyPojo>>() {/* */};
List<MyPojo> res = mapper.convertValue(rows,  typeReference);

来源:https://github.com/FasterXML/jackson/issues/89#issuecomment-882713171