Java 如何从 jersey2 客户端获取 list<String> 作为响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35313767/
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-08-11 16:32:24  来源:igfitidea点击:

How to get list<String> as response from jersey2 client

javajsonjersey-2.0jersey-client

提问by Saurabh

I want to know how I can extract a List<String>as response from the jersey-2.0client.

我想知道如何List<String>jersey-2.0客户端提取响应。

I have already tried this,

这个我已经试过了

List<String> list = client
                      .target(url)
                      .request(MediaType.APPLICATION_JSON)
                      .get(new GenericType<List<String>>(){});

But, the above code is not working. It is not returning the expected List<String>but, a nullvalue instead.

但是,上面的代码不起作用。它不是返回预期的,List<String>而是返回一个null值。

回答by user2004685

You can get your service response as Responseclass object and, then parse this object using readEntity(...)method.

您可以将服务响应作为Response类对象获取,然后使用readEntity(...)方法解析此对象。

Here is a quick code snippet:

这是一个快速的代码片段:

List<String> list = client
                      .target(url)
                      .request(MediaType.APPLICATION_JSON)
                      .get(Response.class)
                      .readEntity(new GenericType<List<String>>() {});
/* Do something with the list object */

回答by Arslan Ahmad

1) Take your Response in the then parse the Response Object using readEntity() method.

1) 获取您的响应,然后使用 readEntity() 方法解析响应对象。

List<String> list = client.target(url).
request(MediaType.APPLICATION_JSON).get(Response.class).readEntity(new GenericType<List<String>>() {
});

回答by Saurabh

String listString= serviceResponse.readEntity(String.class);
Gson gson=new Gson();
Type type = new TypeToken<List<String>>(){}.getType();
List<String> list = gson.fromJson(listString, type);

Get response string and then convert to List by using gson library

获取响应字符串,然后使用 gson 库转换为 List

回答by Ali Yeganeh

First add Hymanson dependency

首先添加Hymanson依赖

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-Hymanson</artifactId>
    <version>2.27</version>
</dependency>

Then create Client Config

然后创建客户端配置

ClientConfig config = new ClientConfig();
config.register( HymansonFeature.class );

Finally create the client through the ClientConfig

最后通过ClientConfig创建客户端

List<String> list = ClientBuilder.newClient( config )
               .target( uri )
               .request()
               .get( Response.class )
               .readEntity( List.class );