我正在尝试用 Dozer 解决这个问题,但没有找到相关信息:
我想使用 Dozer 从 http 请求参数填充一个嵌入式集合。
我可以将请求参数作为 java.util.Map(如下面的“requestMap”)使用,条目如下所示:
Map<String, String> requestMap (key -> value) =
- "id" -> "15"
- "title" -> "Nice article about electric cars"
- "comments[0].text" -> "comment 1"
- "comments[1].text" -> "comment 2"
我要填充的 bean:
public class Article {
int id;
String title;
List<Comment> comments;
}
public class Comment {
String text;
}
当我使用“mapper.map(requestMap, article)”时,文章“标题”和“id”属性会很好地从 map 中填充。但是,“评论”集合不会被填充。
Dozer 是否也应该能够填充集合?我需要做什么才能填充它?
最佳答案
我认为 Dozer
不够聪明,无法将此映射:comments[0].text
到 的
。List
评论
您可以从您的requestMap
中手动提取您的值并从中创建一个列表。
List<Comment> comments = map.entrySet().stream()
.filter(entry -> entry.getKey().startsWith("comments"))
.map(entryTwo -> new Comment(entryTwo.getValue()))
.collect(Collectors.toList());
然后将其包含在您的文章中:
article.setComments(comments);
关于java - 如何使用 map 中的嵌入式集合填充对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46295146/