如何获取列表<字符串>作为 jersey2 客户端的响应

2022-09-01 07:19:48

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

我已经试过了,

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

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


答案 1

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

下面是一个快速代码片段:

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

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

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