簡體   English   中英

如何從Spring RestTemplate中的Object獲取List

[英]How to get List from Object in Spring RestTemplate

如何從對象獲取List? 您可以在下面找到我的代碼:

ResponseEntity<Object> responseEntity = restTemplate.getForEntity("localhost:8083/connectors/", Object.class);
Object object = responseEntity.getBody();

實際上,對象變量是一個對象列表(字符串),我需要獲取所有這些字符串。

如果我打印出System.out.println(object.toString()); 它看起來像那樣:

[objvar, values, test, object, servar, larms, aggregates, sink, records]

我需要將這些字符串列表動態使用它。 能否請你幫忙?

試試吧。 這應該工作。

ResponseEntity<String[]> responseEntity = restTemplate.getForEntity("localhost:8083/connectors/", String[].class);
List<String> object = Arrays.asList(responseEntity.getBody());

對於簡單的情況,上面的代碼可以工作,但是當你想要映射的復雜json結構時,那么理想的是使用ParameterizedTypeReference。

ResponseEntity<List<String>> responseEntity =
        restTemplate.exchange("localhost:8083/connectors/",
            HttpMethod.GET, null, new ParameterizedTypeReference<List<String>>() {
            });
List<String> listOfString = responseEntity.getBody();

如果您確定此對象始終是List ,則只需將其強制轉換

List<?> lst= (List) responseEntity.getBody();

但是,您不能直接將其強制轉換為List<String> ,因此您必須通過循環或流檢查元素類型以生成類型化列表。 使用過的API能否以任何方式返回實際類型?

您可以嘗試將此作為解決方法

List list = java.util.Arrays.asList(object.toString());

或者,您可以使用像ObjectMapper這樣的庫,它直接將json字符串轉換為您想要的模型

這對你有用:

ResponseEntity<Object[]> responseEntity = restTemplate.getForEntity("localhost:8083/connectors/", Object[].class);
List<Object> responseList = Arrays.asList(responseEntity.getBody());

(同樣適用於List []而不是Object [])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM