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

3

36

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

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 null value instead.

Uniocular answered 10/2, 2016 at 11:20 Comment(0)
S
79

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

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 */
Sclerite answered 10/2, 2016 at 11:23 Comment(5)
I am getting size=5 but all elements are null is displayed on debug.But elements are presentUniocular
Can you please share the JSON Response from the Service you are trying to consume?Sclerite
This is the json response ["mumbai","delhi","calcutta"]Uniocular
This is not List<String> but JSONArray. There is a difference.Sclerite
ya thanks,I converted jsonString to list.String listString= serviceResponse.readEntity(String.class) and converted back to jsonArray and then to listUniocular
U
1
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

Uniocular answered 7/9, 2016 at 17:38 Comment(1)
This answer turned up in the low quality review queue, presumably because you don't provide any explanation of the code. If this code answers the question, consider adding adding some text explaining the code in your answer. This way, you are far more likely to get more upvotes — and help the questioner learn something new.Inductor
L
-1

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

List<String> list = client.target(url).
request(MediaType.APPLICATION_JSON).get(Response.class).readEntity(new GenericType<List<String>>() {
});
Lakeshialakey answered 10/2, 2016 at 11:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.