VanDavv
VanDavv

Reputation: 836

How to read JSON request body using Dropwizard

I've been writing simple dropwizard application, and everything worked fine, untill I had to change request type. As I previously got my arguments from Header, now I have to get them from the body of a JSON request. And the saddest part is - there is no complete documentation for dropwizard or any article, that would help me. Here's my code:

@Path("/actors")
@Produces("application/json")
public class ActorResource {
    private final ActorDAO dao;

    public ActorResource(ActorDAO dao) {
        this.dao = dao;
    }

    @POST
    @UnitOfWork
    public Saying postActor(@HeaderParam("actorName") String name,@HeaderParam("actorBirthDate") String birthDate) {
        Actor actor = dao.create(new Actor(name,birthDate));
        return new Saying("Added : " + actor.toString());
    }

Does anyone have a solution?

Upvotes: 2

Views: 14926

Answers (1)

pandaadb
pandaadb

Reputation: 6456

as requested, here's a snippet demonstrating what you want to do:

@Path("/testPost")
@Produces(MediaType.APPLICATION_JSON)
public class TestResource {

    @POST
    public Response logEvent(TestClass c) {
        System.out.println(c.p1);

        return Response.noContent().build();
    }

    public static class TestClass {

        @JsonProperty("p1")
        public String p1;

    }
}

The TestClass is my body. Jersey knows right away, that it needs to parse the body into that object.

I can then curl my API doing this:

curl -v  -XPOST "localhost:8085/api/testPost" -H "Content-Type: application/json" -d '{"p1":"world"}'

Jersey knows by the method parameter what to do, and by the Jackson Annotation how to treat the JSON.

Hope that helps,

Artur

Edit: For the more manual approach, you can:

In your post method, inject

@Context HttpServletRequest request

And from the injected request, write the body into a String for handling:

StringWriter writer = new StringWriter();
        try {
            IOUtils.copy(request.getInputStream(), writer);
        } catch (IOException e) {
            throw new IllegalStateException("Failed to read input stream");
        }

Now use any library to map that string to whatever Object you want.

Upvotes: 9

Related Questions