PART 2: Using JSON with Jersey 2

(This is part of a series

We previously included the import in our build.gradle

compile ''

And created a JerseyApplication that had the line


This allows use to use JSON via the Jackson library with Jersey.

Now create a POJO which we'll use for transmitting the JSON. (Note the @XMLRootElement annotation which means it'll be serialised, into JSON in our case).

echo '
package com.example.YOURPROJECT;

import javax.xml.bind.annotation.XmlRootElement;

public class ExampleResource {
	private String stuff;

	public String getStuff() {
		return stuff;

	public void setStuff(String stuff) {
		this.stuff = stuff;

' > src/main/java/com/example/YOURPROJECT/

Now let's create a new request that will return an array of these objects.

echo '
package com.example.YOURPROJECT;

import java.util.ArrayList;
import java.util.List;


public class ExampleJSONRequest {

    public List<ExampleResource> example() {
        ArrayList<ExampleResource> resList = new ArrayList<ExampleResource>();
        ExampleResource exampleItem = new ExampleResource();
        exampleItem.setStuff("Some stuff");
        ExampleResource exampleItem1 = new ExampleResource();
        exampleItem1.setStuff("Some more stuff");
        return resList;
' > src/main/java/com/example/YOURPROJECT/

The differences from our previous request are that the @Path has changed, we're not longer concerned about a @PathParam, and the @Produces method now says we're returning JSON, not plain text.

Let's now build it, run it and look at the response.

gradle build
java -jar jetty-runner-9.1.0.M0.jar --port 8081 build/libs/YOUR_PROJECT_DIR.war

Then if you go to the url below you will see [{"stuff":"Some stuff"},{"stuff":"Some more stuff"}]

java-jersey java java-web-quick-start

Edit on github
comments powered by Disqus
Click me