Search code examples
javacollectionspojodozer

How to populate an object with embedded collection from a Map?


I am trying to solve this with Dozer and haven't found info on it:

I would like to populate an embedded collection from http request parameters with Dozer.

The request parameters are available for me as a java.util.Map (as 'requestMap" below) and the entries look like this:

Map<String, String> requestMap (key -> value) =
- "id" -> "15"
- "title" -> "Nice article about electric cars"
- "comments[0].text" -> "comment 1"
- "comments[1].text" -> "comment 2"

The beans I would like to populate:

public class Article {
  int id;
  String title;
  List<Comment> comments;
}

public class Comment {
  String text;
}

When I use "mapper.map(requestMap, article)", the article "title" and the "id" attributes get populated from the map nicely. However, the "comments" collection does not get populated.

Is Dozer supposed to be able to populate the collection as well? What do I have to do to get it populated?


Solution

  • I don't think Dozer is smart enough to map this: comments[0].text into a List of Comment.

    You can manually extract your values from yourrequestMap and make a list from it.

    List<Comment> comments = map.entrySet().stream()
                .filter(entry -> entry.getKey().startsWith("comments"))
                .map(entryTwo -> new Comment(entryTwo.getValue()))
                .collect(Collectors.toList());
    

    Then just include it in your article:

    article.setComments(comments);