Van*_*avv 2 java json jackson dropwizard
我一直在编写简单的dropwizard应用程序,一切正常,直到我不得不更改请求类型.因为我之前从Header得到了我的参数,现在我必须从JSON请求的主体中获取它们.最可悲的是 - 没有关于dropwizard或任何文章的完整文档,这对我有帮助.这是我的代码:
@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());
}
Run Code Online (Sandbox Code Playgroud)
有没有人有办法解决吗?
根据要求,这是一个片段,展示你想要做什么:
@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;
}
}
Run Code Online (Sandbox Code Playgroud)
TestClass是我的身体.泽西知道,它需要将身体解析为该物体.
然后,我可以卷起我的API:
curl -v -XPOST "localhost:8085/api/testPost" -H "Content-Type: application/json" -d '{"p1":"world"}'
Run Code Online (Sandbox Code Playgroud)
Jersey知道通过方法参数做什么,并通过Jackson Annotation如何对待JSON.
希望有所帮助,
阿图尔
编辑:对于更手动的方法,您可以:
在你的post方法中,注入
@Context HttpServletRequest request
Run Code Online (Sandbox Code Playgroud)
从注入的请求中,将主体写入String以进行处理:
StringWriter writer = new StringWriter();
try {
IOUtils.copy(request.getInputStream(), writer);
} catch (IOException e) {
throw new IllegalStateException("Failed to read input stream");
}
Run Code Online (Sandbox Code Playgroud)
现在使用任何库将该字符串映射到您想要的任何对象.
| 归档时间: |
|
| 查看次数: |
8674 次 |
| 最近记录: |