我有一个名为 Thing
的简单类
public class Thing {
private int id
private String name
//getters, setters, constructor
}
我想发送一个带有负载的请求并处理它。
请求看起来像这样:
curl -i -d '{"thing": {"id": 11, "name": "foobar"}}' http://localhost:8080/thing/{username}
但我不知道如何处理 json 请求。这就是我的方法:
@Path("/thing/{username}")
@POST
public Thing add(@PathParam("username") String username) {
//how can I process the JSON payload sent and convert it to Thing object?
}
最佳答案
查看 Jackson .
ObjectMapper mapper = new ObjectMapper();
Thing impl = mapper.readValue(username, Thing.class);
只要 username
是有效的 JSON 并映射到 Thing
,这应该可以工作。
注意:您可能需要注释Thing
的类成员或方法。例如,在我的案例中,我必须使用 com.fasterxml.jackson.annotation.JsonManagedReference
来管理循环引用。但是您可以在 API 文档中阅读有关此注释和其他注释的信息。
关于java - 如何使用删除向导处理 JSON 负载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20129556/