Wednesday, February 06, 2013

Custom JSP taglib to convert Object to JSON

The times for direct javascript DOM manipulation are gone. Modern frameworks like Angular.js demand JSON to be available. Finally if you use a hybrid approach where there is a need for server side HTML templates, the need to expose objects in JSON format will be unavoidable.

Using simple JSP views thorugh the help of taglibs should be a clean way to give front end developers what they need. They should be able to get a JSON for their javascript needs in a single line:
  var employees = ${ju:toJson(employees)};
Here is all you need to do in the back-end(middle tier). First you need a utility class that can take an object and serialize it to JSON. The winner in my journey so far is Jackson API so:
package com.nestorurquiza.utils;


import org.codehaus.jackson.JsonGenerationException;

import com.nestorurquiza.serialization.JacksonObjectMapper;

public final class JsonUtils {

 private JsonUtils() {

 public static String toJson(Object value) throws JsonGenerationException, JsonMappingException, IOException {
  JacksonObjectMapper mapper = new JacksonObjectMapper();
  return mapper.writeValueAsString(value);

Here is the custom JsonObjectMapper class:
package com.nestorurquiza.serialization;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JacksonObjectMapper extends ObjectMapper {

 private static final Logger log = LoggerFactory.getLogger(JacksonObjectMapper.class);

 public JacksonObjectMapper() {
  configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);

Here is the taglib descriptor file /WEB-INF/tld/Json.tld:
<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="" xmlns:xsi=""
            String toJson(java.lang.Object)
Finally do not forget to include the taglib to use from JSP:
<%@ taglib prefix="ju" uri="/WEB-INF/tld/JsonUtils.tld"%>

No comments: