如何从 Spring RestTemplate 中的对象获取列表 [英] How to get List from Object in Spring RestTemplate

查看:116
本文介绍了如何从 Spring RestTemplate 中的对象获取列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从对象中获取列表?您可以在下面找到我的代码:

How to get List from Object? Below you can find my code:

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

实际上对象变量是一个对象列表(字符串),我需要获取所有这些字符串.

Actually object variable is a List of Objects(Strings) and I need to get all these Strings.

如果我打印出来 System.out.println(object.toString()); 它看起来像这样:

If I print it out System.out.println(object.toString()); it looks like that:

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

我需要获取这些字符串的列表才能动态使用它.你能帮忙吗?

I need to get List of these Strings to dynamic use it. Could you please help?

推荐答案

试试这个.这应该有效.

Try this out. This should work.

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

对于简单的情况,上面的代码可以工作,但是当您想要映射复杂的 json 结构时,最好使用 ParameterizedTypeReference.

For simple cases the code above works, but when you have complex json structures which you want to map, then it is ideal to use ParameterizedTypeReference.

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

这篇关于如何从 Spring RestTemplate 中的对象获取列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆