Steve Steve - 1 year ago 107
JSON Question

Consuming JSON object in Jersey service

I've been Googling my butt off trying to find out how to do this: I have a Jersey REST service. The request that invokes the REST service contains a JSON object. My question is, from the Jersey POST method implementation, how can I get access to the JSON that is in the body of the HTTP request?

Any tips, tricks, pointers to sample code would be greatly appreciated.



Answer Source

I'm not sure how you would get at the JSON string itself, but you can certainly get at the data it contains as follows:

Define a JAXB annotated Java class (C) that has the same structure as the JSON object that is being passed on the request.

e.g. for a JSON message:

  "A": "a value",
  "B": "another value"

Use something like:

public class C
  public String A;
  public String B;

Then, you can define a method in your resource class with a parameter of type C. When Jersey invokes your method, the JAXB object will be created based on the POSTed JSON object.

public class MyResource
  public put(C c)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download