java post接收json,如何在Java中的RESTful(Web服务)POST方法中接收json对象

It may be bit silly question, but I am confuse if it is possible to receive the JSON Objects in the @FormParam in the POST method under RESTful webservice

@POST

@Produces(MediaType.APPLICATION_JSON)

@Consumes(MediaType.APPLICATION_JSON)

@Path("/fetch/")

public List getCandidate(@FormParam("CodeList")

List codeList)

{

List myobjects = null;

try {

//some code

} catch (Exception e) {

//some exception if occur

}

return myobjects;

}

And what if I want to get the userdefine object in the form param.

@POST

@Produces(MediaType.APPLICATION_JSON)

@Consumes(MediaType.APPLICATION_JSON)

@Path("/fetch/")

public List getCandidate(@FormParam("CodeList")

List formMyObjectList)

{

List myobjects = null;

try {

//some code

} catch (Exception e) {

//some exception if occur

}

return myobjects;

}

Thanks in advance.

解决方案

This is possible however you need to understand what is @FormParam, basically it receive the values from an specific html form, as you probably know @FormParam need to know what is the param you want to take from the request using @FormParam("myParam"), if you want to consume json you need to provide it. So answer is you dont need to use @FormParam to consume JSON

The above means instead of send a pair key/value properties you need to send the full json, obviously you need to generate that json using probably jquery or even javascript then sent that to your endpoint that should be something like.

@POST

@Produces(MediaType.APPLICATION_JSON)

@Consumes(MediaType.APPLICATION_JSON)

@Path("/fetch/")

public List getCandidate(MyBean mybean){}

Where MyBean class need to have the fields that are going to be sent within the JSON. The magic here is thanks to the MessageBodyReader, you should have jackson in your classpath, you can find an example here. Also will be good idea if you read this.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值