How can I send a POJ with a jersey client without manually converting to JSON?

I have a working json service that looks like this:

@POST @Path("/{id}/query") @Consumes(MediaType.APPLICATION_JSON) @Produces(JSON) public ListWrapper query(@Context SecurityContext sc, @PathParam("id") Integer projectId, Query searchQuery) { ... return result } 

The query object looks like this, and when publishing the json representation of this Query object, it works well.

 @XmlRootElement public class Query { Integer id; String query; ... // Getters and Setters etc.. } 

Now I want to fill this object with the client and use the Jersey client to send this Query object to the service and get a JSONObject as a result. I understand that this can be done without first converting it to a json object, and then sending it as a string.

I tried something like this, but I think I missed something.

 public static JSONObject query(Query searchQuery){ String url = baseUrl + "project/"+searchQuery.getProjectId() +"/query"; WebResource webResource = client.resource(url); webResource.entity(searchQuery, MediaType.APPLICATION_JSON_TYPE); JSONObject response = webResource.post(JSONObject.class); return response; } 

I am using Jersey 1.12.

Any help or pointer in the right direction would be greatly appreciated.

+8
java json jackson jersey client
source share
2 answers

If your web service creates JSON, you must process it on your client using the accept() method:

 ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).post(searchQuery, MediaType.APPLICATION_JSON); ListWrapper listWrapper = response.getEntity(ListWrapper.class); 

Try it and give your results.

+3
source share

The WebResource.entity (...) method does not modify your webResource instance ... it creates and returns a Builder object that contains the change. Your .post call is usually made from the Builder object, not from the WebResource object. This transition is easily obscured when all queries are connected together.

 public void sendExample(Example example) { WebResource webResource = this.client.resource(this.url); Builder builder = webResource.type(MediaType.APPLICATION_JSON); builder.accept(MediaType.APPLICATION_JSON); builder.post(Example.class, example); return; } 

In the same example, a chain is used. It still uses Builder, but less obvious.

 public void sendExample(Example example) { WebResource webResource = this.client.resource(this.url); webResource.type(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .post(Example.class, example); return; } 
+5
source share

All Articles