如何使用Map填充嵌入式集合的对象?

时间:2017-09-19 08:06:38

标签: java collections pojo dozer

我正在尝试使用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"

我想填充的豆子:

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

public class Comment {
  String text;
}

当我使用&#34; mapper.map(requestMap,article)&#34;时,文章&#34; title&#34;和&#34; id&#34;属性从地图中很好地填充。然而,&#34;评论&#34;集合没有填充。

Dozer是否应该能够填充该集合?我需要做些什么来填充它?

2 个答案:

答案 0 :(得分:3)

我认为Dozer非常聪明,无法将此comments[0].text映射到List的{​​{1}}。

您可以从Comment手动提取值并从中制作一个列表。

requestMap

然后将其包含在您的文章中:

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

答案 1 :(得分:1)

当然Map可以有收藏。
当您使用地图时,您只能有两个参数 - &gt;例如<?php function is_ping_address($ip) { exec('ping -c1 -w1 '.$ip, $outcome, $status); preg_match('/([0-9]+)% packet loss/', $outcome[3], $arr); return ( $arr[1] == 100 ) ? false : true; }
这就是为什么你需要一个键/ id和一个对象。在这种情况下,您可以映射文章及其ID。

Map<Integer, String>

public class Article { int id; String title; List<String> comments; //IMO you don't need class for comments(comment = string) } 您文章中的Map<Integer, Article>

检查 this 链接,了解如何从Dozer映射集合