如何在java restful服务中使用json参数 [英] How to consume json parameter in java restful service
问题描述
我如何在我的webservice中使用json参数,我可以使用@PathParam获取参数但是获取json数据作为参数不知道该怎么做。
How can i consume json parameter in my webservice, I can able to get the parameters using @PathParam but to get the json data as parameter have no clue what to do.
@GET
@Path("/GetHrMsg/json_data")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces(MediaType.APPLICATION_JSON)
public String gethrmessage(@PathParam("emp_id") String empid) {
}
代替@PathParam使用什么以及稍后如何解析它。
What to use in place of @PathParam and how to parse it later.
推荐答案
我假设您正在讨论使用请求发送的JSON邮件正文。
I assume that you are talking about consuming a JSON message body sent with the request.
如果是这样,请注意虽然没有被禁止,但是GET请求不有请求主体是一个普遍的共识。有关解释原因,请参阅 HTTP GET with request body 问题。
If so, please note that while not forbidden outright, there is a general consensus that GET requests should not have request bodies. See the "HTTP GET with request body" question for explanations why.
我之所以提到这一点,只是因为您的示例显示了GET请求。如果您正在进行POST或PUT,请继续阅读,但如果您确实在项目中执行GET请求,我建议您改为 kondu的解决方案。
I mention this only because your example shows a GET request. If you are doing a POST or PUT, keep on reading, but if you are really doing a GET request in your project, I recommend that you instead follow kondu's solution.
话虽如此,要使用JSON或XML消息体,请包含一个(未注释的)方法参数,该参数本身就是表示消息的JAXB bean。
With that said, to consume a JSON or XML message body, include an (unannotated) method parameter that is itself a JAXB bean representing the message.
所以,如果您的邮件正文如下所示:
So, if your message body looks like this:
{"hello":"world","foo":"bar","count":123}
然后你将创建一个如下所示的相应类:
Then you will create a corresponding class that looks like this:
@XmlRootElement
public class RequestBody {
@XmlElement String hello;
@XmlElement String foo;
@XmlElement Integer count;
}
您的服务方式如下:
@POST
@Path("/GetHrMsg/json_data")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public void gethrmessage(RequestBody requestBody) {
System.out.println(requestBody.hello);
System.out.println(requestBody.foo);
System.out.println(requestBody.count);
}
哪一项会输出:
world
bar
123
< hr>
有关使用JAXB使用不同类型的HTTP数据的更多信息,我建议您查看问题如何在RESTful POST方法中访问参数,这里有一些很棒的信息。
For more information about using the different kinds of HTTP data using JAXB, I'd recommend you check out the question "How to access parameters in a RESTful POST method", which has some fantastic info.
这篇关于如何在java restful服务中使用json参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!