Issue
I have a JSON payload sent as part of POST request body like:
{
"id": "xyz3",
"model": "Camry",
"year": 2010
}
And I would expect this payload to be converted to the instance of my java class CarRequest defined like:
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
...
@XmlRootElement(name = "carRequest")
@XmlAccessorType(XmlAccessType.FIELD)
public class CarRequest {
private String id;
private String model;
private int year;
public CarRequest() {
}
public String getId() {
return id;
}
public String getModel() {
return model;
}
public int getYear() {
return year;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
}
}
However, in my POST endpoint resource method I dont see this happening. My resource is defined as:
@POST
@Path("cars")
@Produces({ "application/json", "application/xml" })
public Response carsInfos(@Valid CarRequest carRequest) {
System.out.println(carRequest); //prints { "id": "null", "model": "null", "year": 0 }
return Response.ok().build();
}
Above, the line that prints carRequest prints it like
{ "id": "null", "model": "null", "year": 0 }
, instead of like
{ "id": "xyz3", "model": "Camry", "year": 2010 }
Solution
I have tried @Consumes annotation (thanks @David M. Karr) but that did not solve anything. It turns out that my server was using JavaEE 8 with JAXRS 2.1 features. After adding features for JavaEE7 and JAXRS 2.0, the request model started getting populated with the values.
Answered By - pixel