tags:

views:

1015

answers:

2

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.

Thanks...

--Steve

A: 

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:

@XmlAccessorType(XmlAccessType.FIELD)
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.

@Path("/resource")
public class MyResource
{
  @POST
  public put(C c)
  {
     doSomething(c.A);
     doSomethingElse(c.B);
  }
}
Andy
Unfortunately, the JSON string is basically being used more as a dictionary than as a real POJO. I'd rather not have to create a new POJO for the JSON objects.
Steve
Have you looked at using a MessageBodyReader (http://jackson.codehaus.org/javadoc/jax-rs/1.0/javax/ws/rs/ext/MessageBodyReader.html). Not tried it myself, but you might be able to get in at that level and convert the JSON stream to a map etc.
Andy
Actually it turns out that its much simpler than I thought. I can get the body of the HTTP request as a string argument, and then process it using any JSON library (currently using Google GSON) to convert the request data into local objects.
Steve
A: 

Submit/POST the form/HTTP.POST with a parameter with the JSON as the value.

@QueryParam jsonString

public desolveJson(jsonString)

doyle
I thought about doing that. It's just not quite the way I'd like to go. There are a few toolkits out there that drop the complete JSON into the actual body of the HTTP request, and I'd like to follow that pattern if possible.
Steve
really? I didn't know you could or should post a body. On a GET you can put the json in the body and I'm in total agreement with that. I wonder if you can use stackoverflow as a task tool with mylyn?
doyle