简体   繁体   中英

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

Prelude: I'm using hibernate 3 with a select that returns only some specified fields. I didn't find a way to get a list of POJOs, the best I found is to return a list of maps using query.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);


I have a list of Map<String, Object> . Now, the way I found to convert it to a list of POJO is with 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);
}

Is there not a simpler way?

You can use a TypeReference:

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

You was near, Yann :-)

I found it, thanks to cowtowncoder :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM