java restful服务中如何使用json参数 [英] How to consume json parameter in java restful service

查看:67
本文介绍了java restful服务中如何使用json参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何在我的 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;
}

您的服务方法将如下所示:

And your service method would look like this:

@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

<小时>

有关使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆