How to get list as response from jersey2 client

后端 未结 4 581
没有蜡笔的小新
没有蜡笔的小新 2020-12-30 23:23

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

I have already tried this,

Li         


        
相关标签:
4条回答
  • 2020-12-30 23:29

    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>>() {
    });
    
    0 讨论(0)
  • 2020-12-30 23:34

    First add jackson dependency

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

    Then create Client Config

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

    Finally create the client through the ClientConfig

    List<String> list = ClientBuilder.newClient( config )
                   .target( uri )
                   .request()
                   .get( Response.class )
                   .readEntity( List.class );
    
    0 讨论(0)
  • 2020-12-30 23:39

    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 */
    
    0 讨论(0)
  • 2020-12-30 23:42
    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

    0 讨论(0)
提交回复
热议问题