简体   繁体   中英

Cannot get JSON data from Jersey GET response

I was developing a restful web client and trying to get the JSON payload from the response of a GET method. I am using Jersey. But I just cannot read the JSON data using response.getEntity() method. I tried many methods including response.bufferEntity(), but the output always kept empty. Below is my code and output, and in addition I can see the JSON data right in the response packet captured in wireshark. I would really appreciate everyone trying to help figure out why or provide solution. Thank you!

Code:

    public JSONObject Get(String requestPath){

    ClientResponse response = webResource.path(requestPath)
            .header("Content-Type", contTypeHeader )
            .header("Accept",acceptHeader)
            .header("Authorization", authZ )
            .get(ClientResponse.class);

    response.bufferEntity();
    if (!(response.getStatus() == 201 || response.getStatus() == 200)) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
    }

    System.out.println(response.getEntity(JSONObject.class));
    return null;

}

and the output is always like this: {}

You can't use JSONObject unless you have a MessageBodyReader for it. See more at JAX-RS Entity Providers . The provider you are currently using (probably Jackson) only supports JavaBean POJOs or collections of them. For example if you have this JSON

{ "property1" : "value1", "property2": "value2" }

Then you would need to have a POJO like

public class Bean {
    private String property1;
    private String property2;
    // getters and setters
}

Then you can do getEntity(Bean.class) . The reason you are getting an empty object, is that the deserialization works off the setters. It looks for properties on the JSON, that matches a setters, and uses it the set the property. The JSON object has no setters for your JSON properties.

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