是否有一种更简单的方法可以使用 Java 或 Jackson 在 Java 7 中的 POJO 列表中转换地图列表?

问题描述

前奏:我使用 hibernate 3 和一个仅返回某些指定字段的选择。我没有找到获取 POJO 列表的方法,我发现的最好方法是使用 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);
}

没有更简单的方法吗?

解决方法

您可以使用类型引用:

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

你就在附近,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