[英]Convert String to List<Map<String, String>>> for tests
I need to convert a String
to List<Map<String, String>>>
for pass JUnit Test.我需要将
String
转换为List<Map<String, String>>>
以通过 JUnit 测试。 I have this:我有这个:
String userAttributes = "[{name=test, cp=458999, lastname=test2}]";
That i want is in the tests (Mockito) change a call to a server with this values, something like this:我想要的是在测试(Mockito)中更改对具有此值的服务器的调用,如下所示:
Mockito.when(template.search(Mockito.anyString, new AttributesMapper()).thenReturn(attributes);
I need List<Map<String, String>>>
for do this:我需要
List<Map<String, String>>>
来做到这一点:
user.setUserName(attributes.get("name"));
Try regex or split by special char.尝试正则表达式或按特殊字符拆分。 First remove parentheses from beginning and end.
首先删除开头和结尾的括号。 After that you can split it by
,
and =
to collect strings to map.之后,您可以将其拆分为
,
和=
以将字符串收集到 map。
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"));
Other approach with Pattern
Pattern
的其他方法
Map<String, String> collect = Pattern.compile(",")
.splitAsStream(userAttributes
.replace("[{","").replace("}]",""))
.map(s -> s.split("="))
.collect(Collectors.toMap(s -> s[0], s -> s[1]));
Or if you really wants use List<Map<String, String>>>
.或者,如果您真的想使用
List<Map<String, String>>>
。 But after that you can not do this user.setUserName(attributes.get("name"));
但在那之后你不能这样做
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);
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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.