Search code examples
jsonspringspring-bootspring-webclient

How can I collect list with WebClient in Spring Boot


I want to collect data the following for an Object.

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

Our object like this;

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

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

How can I collect JSON Data with WebClient in Spring Boot ?

Thanks


Solution

  • You should create a model that matches the WebClient response:

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

    And use it as follows:

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

    Now all you need is to map the Response object to Currencies.

    Additionally, you should definitely avoid using block(). It defeats the whole purpose of using WebFlux.