Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

json

jax-rs

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.

like image 868
V G Avatar asked Jul 31 '13 12:07

V G


2 Answers

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);
}
like image 148
TheArchitect Avatar answered Sep 22 '22 01:09

TheArchitect


According to this documentation there are 6 parameter-based annotations used to extract parameters from a request, and no one seems to be for JSON parameters.

like image 31
V G Avatar answered Sep 19 '22 01:09

V G