16
Jul

Using Apache Sling with Jackson to output JSON/XML

Writing JSON using Sling’s built-in API is fun and fast, however there are alternatives that can make the coding smoother.

One interesting alternative is to use Jackson ( https://github.com/FasterXML ) libs.

First step is to install the following Jackson bundles into Sling ( v. 2.2.2 is the latest version at the time this tutorial has been written ):

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.2.2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.2.2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.2.2</version>
</dependency>

Then, to test the integration you can create 2 classes: a POJO and a Servlet exposing the POJO:

@XmlRootElement
public class User
{
    private String name = "hello jackson";
 
    public String getName()
    {
        return test;
    }
 
    public void setName(String test)
    {
        this.test = test;
    }
}

And the Apache Sling Servlet:

@Component
@Service(Servlet.class)
@Properties({ @Property(name="service.description", value="Jackson Test Servlet"),
    @Property(name="sling.servlet.paths", value="/bin/jackson-test")
})
public class TestJacksonOutputServlet  extends SlingSafeMethodsServlet
{
    @Override
    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
            throws ServletException, IOException
    {
        User user = new User();
        ObjectMapper mapper = new ObjectMapper();
        String jsonOutput = mapper.writeValueAsString(user);
 
        response.getWriter().write(jsonOutput);
    }
}

That’s it and it’s really simple.