I am facing issues while consuming JAX-RS services as JSON.
Below I have added my code.
This is my service class:
//Sets the path to base URL
You have to convert the response to JSON using Gson.toJson(object)
.
For example:
return Response.status(Status.OK).entity(new Gson().toJson(Student)).build();
You've to create empty constructor because JAX-RS initializes the classes... Your constructor must have no arguments:
@XmlRootElement
public class Student implements Serializable {
public String first_name;
public String last_name;
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public Student()
{
first_name = "Fahad";
last_name = "Mullaji";
}
public Student()
{
}
}
Ensure that you have following JARS in place: 1) jackson-core-asl-1.9.13 2) jackson-jaxrs-1.9.13 3) jackson-mapper-asl-1.9.13 4) jackson-xc-1.9.13
I was in the same situation where
- I was not using Maven or Ant,
- I finished this Vogella tutorial on Jersey,
- and I was getting the MessageBodyWriter
error when trying to use @Produces(MediaType.APPLICATION_JSON)
.
This answer by @peeskillet solves the problem - you have to use the Jackson *.jar files that are available from the FasterXML Jackson Download page. You'll need the core
files as well as the jaxrs
files.
I added them to my WebContent/WEB-INF/lib
folder where I have my Jersey *.jar files per the above tutorial, and made the small change to the web.xml file below (again, as originally shared by @peeskillet):
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>
your.other.package.here, com.fasterxml.jackson.jaxrs.json
</param-value>
The important part being com.fasterxml.jackson.jaxrs.json
.