Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JSON query parameters to objects with JAX-RS

I have a JAX-RS resource, which gets its paramaters as a JSON string like this:

http://some.test/aresource?query={"paramA":"value1", "paramB":"value2"} 

The reason to use JSON here, is that the query object can be quite complex in real use cases.

I'd like to convert the JSON string to a Java object, dto in the example:

@GET  @Produces("text/plain") public String getIt(@QueryParam("query") DataTransferObject dto ) {     ... } 

Does JAX-RS support such a conversion from JSON passed as a query param to Java objects?

like image 261
deamon Avatar asked Apr 23 '10 09:04

deamon


2 Answers

Yes, you can do this, but you will need to write the conversion code yourself. Fortunately, this is easy, you just need to write a class that has a public String constructor to do the conversion. For example:

public class JSONParam {     private DataTransferObject dto;      public JSONParam(String json) throws WebApplicationException {         try {             // convert json string DataTransferObject and set dto         }         catch (JSONException e) {             throw new WebApplicationException(Response.status(Status.BAD_REQUEST)                     .entity("Couldn't parse JSON string: " + e.getMessage())                     .build());         }     }      public DataTransferObject getDTO() {         return dto;     } } 

Then you can use:

@GET  @Produces("text/plain") public String getIt(@QueryParam("query") JSONParam json) {     DataTransferObject dto = json.getDTO();     ... } 
like image 74
Jason Day Avatar answered Sep 25 '22 15:09

Jason Day


As mentioned, you do need to explicitly convert from String parameter to JSON. But there is no need to use something as primitive as org.json's parser; Jackson or Gson can do data binding (String to JSON, JSON to POJO) in a line or two. With Jackson:

MyValue value = new ObjectMapper().readValue(json, MyValue.class); 

(for production code, just create ObjectMapper once as static member, reuse)

Jackson is what most JAX-RS implementations use to implement data-binding for POST data, so this is quite similar.

like image 25
StaxMan Avatar answered Sep 22 '22 15:09

StaxMan