【问题标题】:How can I collect list with WebClient in Spring Boot如何在 Spring Boot 中使用 WebClient 收集列表
【发布时间】:2021-11-16 08:29:39
【问题描述】:

我想为一个对象收集以下数据。

{
"success": true,
"symbols": {
"AED": "United Arab Emirates Dirham",
"AFN": "Afghan Afghani",
"ALL": "Albanian Lek"
     }
}

我们的对象是这样的;

public class Currencies {
    public String success;
    public List<ExternalCurrency> currencyList;
}

public class ExternalCurrency {
    public String shortCode;
    public String name;
}

如何在 Spring Boot 中使用 WebClient 收集 JSON 数据?

谢谢

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 我尝试使用 json2csharp.com/json-to-pojo 。但它给了我两个类以下 public class ExternalCurrency { @JsonProperty("AED") public String aED; @JsonProperty("AFN") 公共字符串 aFN; @JsonProperty("ALL") public String all; } 公共类货币{ 公共布尔成功;公共外部货币符号;我不想这样。因为也许明天我会添加一种新货币
  • 最终 WebClient webClient = WebClient.builder().baseUrl("-----").build();最终货币数据= webClient.get().retrieve().bodyToMono(Currencies.class).block();

标签: json spring spring-boot spring-webclient


【解决方案1】:

您应该创建一个与WebClient 响应匹配的模型:

public class Response {
    public String success;
    public Map<String, String> symbols;
}

并按如下方式使用:

WebClient webClient = WebClient.builder().baseUrl("-----").build(); 
Response response = webClient.get().retrieve().bodyToMono(Response.class).block();

现在您只需将Response 对象映射到Currencies

此外,您绝对应该避免使用block()。它违背了使用 WebFlux 的全部目的。

【讨论】:

  • 这对我有用,谢谢 :)
  • 太棒了!如果您愿意,请接受答案,以便其他人可以轻松找到类似问题的解决方案;)
猜你喜欢
  • 2019-04-15
  • 1970-01-01
  • 2021-04-10
  • 2020-12-23
  • 2019-12-20
  • 2019-01-14
  • 1970-01-01
  • 1970-01-01
  • 2021-10-29
相关资源
最近更新 更多