我需要将String
转换为List<Map<String, String>>>
才能通过JUnit测试。我有这个:
String userAttributes = "[{name=test, cp=458999, lastname=test2}]";
我想要在测试中(Mockito)使用此值更改对服务器的调用,如下所示:
Mockito.when(template.search(Mockito.anyString, new AttributesMapper()).thenReturn(attributes);
我需要List<Map<String, String>>>
来做到这一点:
user.setUserName(attributes.get("name"));
答案 0 :(得分:0)
尝试使用正则表达式或按特殊字符分隔。首先从开头和结尾删除括号。之后,您可以将其分为,
和=
以收集要映射的字符串。
String userAttributes = "[{name=test, cp=458999, lastname=test2}]";
List<String> strings = Arrays.asList(userAttributes
.replace("[{","").replace("}]","")
.split(", "));
Map<String, String> collect = strings.stream()
.map(s -> s.split("="))
.collect(Collectors.toMap(s -> s[0], s -> s[1]));
System.out.println(collect.get("name"));
使用Pattern
Map<String, String> collect = Pattern.compile(",")
.splitAsStream(userAttributes
.replace("[{","").replace("}]",""))
.map(s -> s.split("="))
.collect(Collectors.toMap(s -> s[0], s -> s[1]));
或者如果您确实要使用List<Map<String, String>>>
。但是之后,您将无法执行此操作user.setUserName(attributes.get("name"));
List<Map<String, String>> maps = strings.stream()
.map(s -> s.split("="))
.map(s -> Map.of(s[0], s[1]))
.collect(Collectors.toList());
System.out.println(maps);
答案 1 :(得分:0)
String userAttributes = "[{name=test, cp=458999, lastname=test2}]";
StringTokenizer stringTokenizer = new StringTokenizer(userAttributes,",");
List<Map<String,String>> list = new ArrayList<>();
while(stringTokenizer.hasMoreElements()){
StringTokenizer stringTokenizer2 = new StringTokenizer((String)stringTokenizer.nextElement(),"=");
while(stringTokenizer2.hasMoreElements()){
Map<String, String> map = new HashMap<>();
map.put( ((String)stringTokenizer2.nextElement()),((String)stringTokenizer2.nextElement()) );
list.add(map);
}
}
System.err.println(list.toString());