JAX-RS Jersey + JSONP Example

Datetime:2016-08-22 23:47:36         Topic: JSONP          Share        Original >>
Here to See The Original Article!!!

This tutorial explains how to use JSONP JSON provider with Jersey 2.x . JSONP is also auto-discoverable just like what we discussed inJersey MOXy example.

Table of Contents

JSONP maven dependencies/changes
Model bean changes
Manually adding JsonProcessingFeature

JSONP maven dependencies/changes

JSONP media module is one of the modules in Jersey 2.x where you don’t need to explicitly register it’s features e.g. JsonProcessingFeature . Once Jersey detects added it’s presence in class path, it automatically registers it. So just add JSONP dependency in pom.xml does half work.



At Service side, where your APIs are written, you need to enable JSON media types using @Produces(MediaType.APPLICATION_JSON) annotation.


public class JerseyService 
	public Employees getAllEmployees() 
		Employees list = new Employees();
		list.setEmployeeList(new ArrayList<Employee>());
		list.getEmployeeList().add(new Employee(1, "Lokesh Gupta"));
		list.getEmployeeList().add(new Employee(2, "Alex Kolenchiskey"));
		list.getEmployeeList().add(new Employee(3, "David Kameron"));
		return list;

Model bean changes

At model beans side, you don’t need to put any annotation or any configuration. It will work by default. You even don’t need to put any root annotation as well.


public class Employees 
	private List<Employee> employeeList;

	public List<Employee> getEmployeeList() {
		return employeeList;

	public void setEmployeeList(List<Employee> employeeList) {
		this.employeeList = employeeList;


public class Employee 
	private Integer id;
	private String name;
	public Employee() {
	public Employee(Integer id, String name) {
		this.id  = id;
		this.name = name;

	public Integer getId() {
		return id;

	public void setId(Integer id) {
		this.id = id;

	public String getName() {
		return name;

	public void setName(String name) {
		this.name = name;
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + "]";

Manually adding JsonProcessingFeature

Though org.glassfish.jersey.jsonp.JsonProcessingFeature is registered automatically, if you wish to register it manually, you can add it in configuration as below.

public class CustomApplication extends ResourceConfig 
	public CustomApplication() 
		property(JsonGenerator.PRETTY_PRINTING, true);


And add this Application class in web.xml file.

 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >


	<display-name>Archetype Created Web Application</display-name>




Drop me your question and comments below.

Happy Learning !!

Reference : https://jersey.java.net/documentation/latest/media.html#json.json-p

About List