Home/Tutorials/RESTful Web Services/JSON Response from Request
RESTful Web Services2 min read

JSON Response from Request

In this tutorial you will see how response comes in form of JSON for a RESTful web service.

JSON Response from REST Request call

Conversion from object to XML is done through JAXB annotation. We have annotated all the resources class with @XmlRootElement, which internally converts Java to XML. This is already implemented in Java, so we do not have to do much.

But conversion from object to JSON cannot be done implicitly by Java. So we need to add an extra library called, moxy, as dependency in our project's pom.xml file.

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-moxy</artifactId>
    <version>2.25.1</version>
</dependency>

Once you add the dependency in pom.xml file, and build the project, moxy jar file will be inlcuded in the refrenced libraries of your project.

JSON Response from Request


Now all you have to do is change the media type mentioned with the @Produces annotation before the methods, to JSON.

@GET
@Produces({MediaType.APPLICATION_JSON})
public List<Course> getAllCourses(@Context HttpHeaders headers)
{
	List<Course> courses = courseService.getAllCourses();
	return  courses;	
}

Now this method will start returning JSON repsonse in the message body. The Moxy library takes care of converting the Java object into JSON.



INTERACTIVE SIMULATION CHALLENGE+250 XP
Workbench Verification

Ready to test "JSON Response from Request" in production?

See how RESTful Web Services algorithms and server loops perform under 100k req/s traffic spikes.

Simulator: SysDesign Ops Simulator