2
votes

I have tested a Rest API using postman and while testing on selection raw option, it shows unsupported media for application/json header content type, but only working with url-encoded form. Please specify how to use @FormParam for application/json content type. Thanks in advance.

1

1 Answers

5
votes

The @FormParam annotation is only used to access parameters passed in a normal form that usually uses x-www-form-urlencoded. If you're sending your data as a JSON in request body, you can just create a POJO class corresponding to your request body containing all properties of your JSON request and use it as the parameter of your REST method. The JAX-RS container automatically deserializes the JSON body of the request into the given object for you.

As an example, if your request body is something like this:

{
    "firstName" : "Foo",
    "lastName"  : "bar"
}

Then you can define a POJO representing your request data as below:

public class PersonRequest {
    private String firstName;
    private String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

And define your REST endpoint to access this data as:

@POST
@Path("/persons")
@Consumes("application/json")
public String savePerson(PersonRequest personRequestData) {
    // request data are deserialized into the personRequestDataas properties 
    System.out.println(personRequestData.getFirstName());

}

You don't need to specify any sort of annotation on your POJO class.