简体   繁体   中英

how to get the result of restful web service with httpClient in json format

I'm developing an httpclient application that use a list<OBJECT> from a RESTful web service in JSON format.

I want to use this result in JSON format.

This is my httpclient application class :

public class ClientAbortMethod {

    public final static void main(String[] args) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpget = new HttpGet("http://localhost:8080/structure/alldto");

            System.out.println("Executing request " + httpget.getURI());
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {

              String data= EntityUtils.toString(response.getEntity());


                System.out.println(data);
                // Do not feel like reading the response body
                // Call abort on the request object
                httpget.abort();
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }

}

This is the result of executing this code

[{"ids":"#AB","champs":[ {"idChamp":1,"order":1,"type":"FROM"},{"idChamp":2,"order":2,"type":"TO"},{"idChamp":3,"order":3,"type":"TEXT"}]},{"ids":"#AC","champs":[{"idChamp":4,"order":1,"type":"FROM"},{"idChamp":5,"order":2,"type":"TO_MAIL"},{"idChamp":6,"order":3,"type":"TEXT"}]},{"ids":"tt","champs":[]}]

This is the restful web service

@RequestMapping("/alldto")
public List<StructureNotificationDto> GetALLStructureNotification() {
     return StructureNotif.StructureDTOS();
}

How can I get the result of this web service in JSON format or other easy-to-manipulate format?

You can use Jackson library. To add libraries, I suggest a dependency management system, like Maven . After that, use the following code:

   ObjectMapper mapper = new ObjectMapper();
   List<StructureNotificationDto> list = mapper.readValue(data, new TypeReference<List<StructureNotificationDto>>() {});

Then you can manipulate the data.

Maybe you want to convert the JSON String into Java Object, so you can manipulate it easily. You can use org.json for that purpose.

Please refer to this question.

You want to manually convert the JSON response String to Java object using Jackson, GSON. Here is the example for converting JSON string to Java Object using GSON and Jackson

ClientResponse response = resourse.type(MediaType.APPLICATION_JSON).get(ClientResponse.class);
if(response.getStatus() == 200)
    return response.getEntity(String.class);
ObjectMapper mapper = new ObjectMapper();
ConfToggleBO togleObj = mapper.readValue(enitity, ConfToggleBO.class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM