Em Ae
Em Ae

Reputation: 8724

Posting JSON via Jersey

I have this code

    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    client.addFilter(new HTTPBasicAuthFilter(adminUser, adminPass));
    client.addFilter(new LoggingFilter(System.out));

    WebResource service = client.resource(baseURL);
    ClientResponse clientResponse = service.path("api")
            .path("v1")
            .path("shoppers")
            .path(orderId)
            .path("status.json").accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, request);

Whenever i try to post a JSON requestl ike that, I am getting HTTP 415 error response. A little digging into this issue revealed that JERSEY isn't marshalling my object properly. By adding the LoggingFilter, I can see that in request body, the JAXBObject was marshed to XML and not JSON.

Is it a known behaviour of JERSEY? What should i do here ?

Upvotes: 0

Views: 4081

Answers (1)

Brendan Long
Brendan Long

Reputation: 54302

You probably need to call type() on your request to set the content-type (I assume Jersey does something smart with this):

.path("status.json")
.type(MediaType.APPLICATION_JSON) // <-- This line
.accept(MediaType.APPLICATION_JSON)
.post(ClientResponse.class, request);

Other resources indicate that you may need to do this manually with an ObjectMapper:

ObjectMapper mapper = new ObjectMapper();
String jsonStr = mapper.writeValueAsString(jsonObj);

Upvotes: 1

Related Questions