有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何以JSON格式保存对象并将其放入控制器中的列表或映射中

我使用远程REST API: http://bank.pl/api/exchangerates/rates/**{table}/{code}**/

我想下载3个项目,同时输入3种货币的**{code}**代码:美元、欧元、英镑,如{code}3种货币的字符串:美元、欧元、英镑

{table}参数是常量,不改变C

   private final String URI_CURRENCY_PATH_ID = "http://bank.pl/api/exchangerates/rates/C/{code}";
     
    @Autowired
    RestTemplate restTemplate;
     
    // Using RestTemplate
     
    
     
   //"C/{code}"
    Map <String, String> params = new HashMap <String, String> ();
    params.put ("C", "USD");
    Currency currency = restTemplate.getForObject (URI_CURRENCY_PATH_ID, Currency.class, params);

如果我使用POSTMAN,我会得到3个对象:

{"table":"C","currency":"dolar amerykański","code":"USD","rates":[{"no":"186/C/NBP/2021","effectiveDate":"2021-09-24","bid":3.8897,"ask":3.9683}]}

{"table":"C","currency":"euro","code":"EUR","rates":[{"no":"186/C/NBP/2021","effectiveDate":"2021-09-24","bid":4.5664,"ask":4.6586}]}

{"table":"C","currency":"funt szterling","code":"GBP","rates":[{"no":"186/C/NBP/2021","effectiveDate":"2021-09-24","bid":5.3426,"ask":5.4506}]}

是否可以使用列表或地图作为直接保存同时获取3种货币

也许有人会尽可能地帮助解决这个问题


共 (1) 个答案

  1. # 1 楼答案

    从API来看,它似乎只接受一个参数。在这种情况下,您不能一次调用带有多个参数的API并返回您正在寻找的响应。但是,可以使用不同的参数并行调用API,这样就不必等到一个API调用响应。下面是代码片段,您可以参考它来并行调用API,这基本上解决了您的问题

    @Service
    public class RestService {
    
        private final String URI_CURRENCY_PATH_ID = "http://bank.pl/api/exchangerates/rates/C/{code}";
    
        @Autowired
        private RestTemplate restTemplate;
    
        Executor executor = Executors.newFixedThreadPool(5);
    
        public void callApi() {
            Map<String, String> map = new HashMap<>();
            CompletableFuture<Currency> apiCall1 = CompletableFuture.supplyAsync(() -> callRestApi(map), executor).thenApply(jsonNode -> callRestApi(jsonNode));
            CompletableFuture<Currency> apiCall2 = CompletableFuture.supplyAsync(() -> callRestApi(map), executor).thenApply(jsonNode -> callRestApi(jsonNode));
            CompletableFuture<Currency> apiCall3 = CompletableFuture.supplyAsync(() -> callRestApi(map), executor).thenApply(jsonNode -> callRestApi(jsonNode));
            List<Currency> result = Stream.of(apiCall1, apiCall2, apiCall3)
                    .map(CompletableFuture::join)
                    .collect(Collectors.toList());
        }
    
        private JsonNode callRestApi(final Map<String, String> params) {
            return restTemplate.getForObject (URI_CURRENCY_PATH_ID, JsonNode.class, params);
        }
    
        private Currency callRestApi(final JsonNode jsonNode) {
            // deserialize it and return your Currency object
            return new Currency(); // just for example
        }
    
        // Keep it somewhere in Model package (here just for example)
        private class Currency {
            // define your arguments
        }
    }