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
.
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With