[英]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. 我一直在编写简单的dropwizard应用程序,一切正常,直到我不得不更改请求类型。 As I previously got my arguments from Header, now I have to get them from the body of a JSON request. 因为我之前从Header得到了我的参数,现在我必须从JSON请求的主体中获取它们。 And the saddest part is - there is no complete documentation for dropwizard or any article, that would help me. 最可悲的是 - 没有关于dropwizard或任何文章的完整文档,这对我有帮助。 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? 有没有人有办法解决吗?
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. TestClass是我的身体。 Jersey knows right away, that it needs to parse the body into that object. 泽西知道,它需要将身体解析为该物体。
I can then curl my API doing this: 然后,我可以卷起我的API:
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. Jersey知道通过方法参数做什么,并通过Jackson Annotation如何对待JSON。
Hope that helps, 希望有所帮助,
Artur 阿图尔
Edit: For the more manual approach, you can: 编辑:对于更手动的方法,您可以:
In your post method, inject 在你的post方法中,注入
@Context HttpServletRequest request
And from the injected request, write the body into a String for handling: 从注入的请求中,将主体写入String以进行处理:
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. 现在使用任何库将该字符串映射到您想要的任何对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.