【问题标题】:Spring Boot 2 WebClient response convert JSON to HashMapSpring Boot 2 WebClient 响应将 JSON 转换为 HashMap
【发布时间】:2019-05-17 05:47:15
【问题描述】:

我想从 WebClient 获得响应并将其转换为仅 Map 而不为响应创建任何类。可能吗?所以我想要下面这样的东西。下面的代码不是有效的代码,它只是我想要的一个想法。

public Map<String, String> someFunction() {
    return webClient.post()
            .uri("/some/path")               
            .retrieve()
            .bodyToFlux(HashMap.class)
            .block();

【问题讨论】:

    标签: java spring spring-boot webclient reactive


    【解决方案1】:

    我会首先尝试将响应对象转换为字符串,并确保我接受 JSON 类型作为回报。一旦我将响应转换为字符串,您可以尝试使用 fastxml 的 jackson 数据绑定库,该库可以将 JSON 字符串转换为 Hashmap。

    例如

    ObjectMapper mapper = new ObjectMapper();
    String json = "{\"name\":\"abc\", \"age\":25}";
    
    Map<String, Object> map = new HashMap<String, Object>();
    
    // convert JSON string to Map
    map = mapper.readValue(json, new TypeReference<Map<String, String>>(){});
    
    System.out.println(map);
    

    这里是databind库和核心库java docs链接

    jackson-databind

    jackson-core

    【讨论】:

    • 谢谢。这个想法可能有效,但它比创建一个类更复杂 :) 我的想法是找到一种方法来在 WebClient 之外创建一个 Map。我只需要整个 JSON 响应中的一个值并创建一个类来获得看起来不是最好的解决方案。
    【解决方案2】:

    如果您对保存 LOC 感兴趣,您可能需要查看核心 Spring Framework 类:ParameterizedTypeReference&lt;T&gt;,找到 here

    public Map<String, String> someFunction() {
        return webClient.post()
                .uri("/some/path")               
                .retrieve()
                .bodyToFlux(new ParameterizedTypeReference<Map<String,String>>(){})
                .block();
    }
    

    干杯。

    【讨论】:

      【解决方案3】:

      我是这样解决的:

      public Map<String, String> someFunction() {
          return webClient.post()
                  .uri("/some/path")               
                  .retrieve()
                  .bodyToFlux(TypedMap.class)
                  .block();
      }
      
      private static class TypedMap extends HashMap<String, String>{}
      

      【讨论】:

        猜你喜欢
        • 2022-01-19
        • 2023-02-15
        • 2014-09-04
        • 2020-08-26
        • 1970-01-01
        • 2016-02-25
        • 2019-04-19
        • 1970-01-01
        • 2018-06-02
        相关资源
        最近更新 更多