Search code examples
jsonjersey

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.

Thanks...

--Steve


Solution

  • 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);
      }
    }