java restful json,如何在java restful服务中使用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) {

}

What to use in place of @PathParam and how to parse it later.

解决方案

I assume that you are talking about consuming a JSON message body sent with the request.

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.

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.

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);

}

Which would output:

world

bar

123

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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值