【问题标题】:Convert String to List<Map<String, String>>> for tests将 String 转换为 List<Map<String, String>>> 以进行测试
【发布时间】:2020-02-21 16:30:45
【问题描述】:

我需要将 String 转换为 List&lt;Map&lt;String, String&gt;&gt;&gt; 以通过 JUnit 测试。我有这个:

String userAttributes = "[{name=test, cp=458999, lastname=test2}]";

我想要的是在测试 (Mockito) 中更改对具有此值的服务器的调用,如下所示:

Mockito.when(template.search(Mockito.anyString, new AttributesMapper()).thenReturn(attributes);

我需要 List&lt;Map&lt;String, String&gt;&gt;&gt; 来执行此操作:

user.setUserName(attributes.get("name"));

【问题讨论】:

  • 提供答案而不是编辑您的问题以添加解决方案部分。
  • 你能说如果给定的答案解决了你的问题,或者说他们有什么问题吗?对答案作出回应有助于将来准确回答。

标签: java spring-boot junit mockito


【解决方案1】:

尝试正则表达式或按特殊字符拆分。首先删除开头和结尾的括号。之后,您可以将其拆分为,= 以收集要映射的字符串。

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&lt;Map&lt;String, String&gt;&gt;&gt;。但是之后你就不能这样做了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);

【讨论】:

    【解决方案2】:
        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());
    

    【讨论】:

    • 您没有删除“[{”和“}]”
    • 如果使用 StringTokenizer 则不需要。
    • 运行此代码并:[{[{name=test}, { cp=458999}, { lastname=test2}]}]
    • 或者list.stream().forEach(m -&gt; System.out.println(m.entrySet()));你得到密钥 "{name" , "cp", "lastname"
    猜你喜欢
    • 1970-01-01
    • 2016-07-21
    • 2021-12-21
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    • 2020-04-01
    • 2018-09-06
    • 1970-01-01
    相关资源
    最近更新 更多