How to POST JSON request to a Jersey REST service?

RajV picture RajV · Mar 15, 2012 · Viewed 7.7k times · Source

I can successfully post XML data to my service, but, trying to do the same using JSON is failing. The POJO is:

@XmlRootElement
public class Address {
    String city;
    String zip;
    //Getters & setters...
}

The service resource is:

@POST
@Produces("application/json")
public Address fix(Address a) {
    return a;
}

I am doing a POST as follows:

POST /AcmeWeb/svc/simple HTTP/1.1
Content-Length: 30
Content-Type: application/json; charset=UTF-8

{"city":"Miami","zip":"33130"}

The server is responding with a 400 Bad Request. I scoured the Internet but found no good example of posting JSON. Any help is appreciated. Thanks.

Answer

Martin Matula picture Martin Matula · Mar 15, 2012

Add @Consumes("application/json") annotation to your fix() method.

Update: This works for me:

Resource method:

@POST
@Produces("application/json")
@Consumes("application/json")
public Address post(Address addr) {
    return addr;
}

Address class:

@XmlRootElement
public class Address {
    public String city;
    public String zip;
}

This is the request I am sending:

Accept  application/json
Content-Type    application/json; charset=UTF-8

{"city":"Miami","zip":"33130"}

This is what I get as a response:

{"city":"Miami","zip":"33130"}