Get simple JSON Parameter from a JSON request in JAX-RS

java, jax-rs, json

Solution

You may create a Java class that reflects the data model of your JSON object and annotate it with JAXB's @XmlRootElement. You can map the attributes to custom JSON key name with @XmlElement annotations, e.g.:

@XmlRootElement
public class MyJSONOject{
    @XmlElement(name="json-key-name")
    public String attribute;
}

Then Jersey can decode the JSON object for you transparently and voila!

@Path("/process-something")
@POST
@Produces("application/json")
@Consumes("application/json")
public AResponse processSomething(MyJSONOject json) {
    log.fine(json.attribute);
}

Problem

The client/browser makes a JSON request to my rest resource (the content-type of the request is `application/json` and the corresponding REST method is `@Consumes("application/json")` annotated). ``` @Path("/process-something") @POST @Produces("application/json") @Consumes("application/json") @HandleDefaultExceptions public AResponse processSomething(List<Long>) { } ``` The JSON body consists of some simple types, like `List<Long>` or `String`. Is there a simple possibility to get JSON parameters injected just annotating it somehow, similar to `@FormParam` in the case of a `application/x-www-form-urlencoded` request? I would like some other easier solutions than decoding the JSON String with Jackson's `ObjectMapper` or Jettison's `JSONObject`.

Original source