Sudhanshu Sharma
Sudhanshu Sharma

Reputation: 314

How to receive json object in the RESTful (WEB SERVICE) POST method in Java

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<MyObject> getCandidate(@FormParam("CodeList")
List<String> codeList)
{
    List<MyObject> 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<MyObject> getCandidate(@FormParam("CodeList")
List<MyObject> formMyObjectList)
{
    List<MyObject> myobjects = null;
    try {
        //some code
    } catch (Exception e) {
        //some exception if occur 
    }
    return myobjects;
}

Thanks in advance.

Upvotes: 2

Views: 7690

Answers (1)

Koitoer
Koitoer

Reputation: 19533

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<MyObject> 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.

Upvotes: 3

Related Questions