java 如何从 Spring RestTemplate 中的对象获取列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49752137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 10:25:59  来源:igfitidea点击:

How to get List from Object in Spring RestTemplate

javajsonspringrestarraylist

提问by Tom

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.

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

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

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

[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?

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

回答by pvpkiran

Try this out. This should work.

试试这个。这应该有效。

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

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.

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

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

回答by meShakti

You can try this as a workaround

你可以试试这个作为解决方法

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

Alternatively you can use Libraries like ObjectMapper, Which directly converts the json strings to your desired model

或者你可以使用像ObjectMapper这样的库 ,它直接将 json 字符串转换为你想要的模型

回答by HBo

If you're sure that this object will always be a List, just cast it

如果您确定此对象将始终为 a List,只需将其强制转换

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

However, you can't directly cast it as a List<String>, so you'll have to check the elements type by a loop or a stream to produce a typed list. Any way that the used API can return the actual type?

但是,您不能直接将其转换为List<String>,因此您必须通过循环或流检查元素类型以生成类型化列表。使用的 API 可以返回实际类型的任何方式?

回答by Avisho

This will work for you:

这对你有用:

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

(Same goes for List[] instead of Object[])

(同样适用于 List[] 而不是 Object[])