java 在 PUT Restful 服务中使用 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5719283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Consume JSON Object in PUT Restful Service
提问by ffleandro
I'm trying to implement a RESTful Service in Java that receives a JSON Object through a PUT request and automatically maps into a Java Object. I managed to do this in XML, but I can't do it using JSON. Here's what I want to do:
我正在尝试在 Java 中实现一个 RESTful 服务,它通过 PUT 请求接收一个 JSON 对象并自动映射到一个 Java 对象。我设法在 XML 中执行此操作,但无法使用 JSON 执行此操作。这是我想要做的:
@PUT
@Consumes(MediaType.APPLICATION_XML)
public String putTodo(JAXBElement<Route> r) {
Route route = r.getValue();
route.toString();
System.out.println("Received PUT XML Request");
return "ok";
}
This works, but using JSON would be something similar, but I can't use JAXB, can I?
这有效,但使用 JSON 会类似,但我不能使用 JAXB,对吗?
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public String putTodo(<WHAT DO I PUT HERE>) {
Route route = r.getValue();
route.toString();
System.out.println("Received PUT JSON Request");
return "ok";
}
采纳答案by bdoughan
By default Jersey will use JAXB to process the JSON messages by leveraging the Jettisonlibrary.
默认情况下, Jersey 将使用 JAXB 通过利用Jettison库来处理 JSON 消息。
So you can do the following:
因此,您可以执行以下操作:
@PUT
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public String putTodo(JAXBElement<Route> r) {
Route route = r.getValue();
route.toString();
System.out.println("Received PUT XML/JSON Request");
return "ok";
}
For More Information on Using Jettison with JAXB:
有关在 JAXB 中使用 Jettison 的更多信息: