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:
<script>
  var employees = ${ju:toJson(employees)};
</script>
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 java.io.IOException;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;

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.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
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="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemalocation="http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
    version="2.0">
    <tlib-version>2.1</tlib-version>
    <uri>JsonUtils</uri>
     
    <function>
        <name>toJson</name>
        <function-class>com.nestorurquiza.utils.JsonUtils</function-class>
        <function-signature>
            String toJson(java.lang.Object)
        </function-signature>
    </function>
</taglib>
Finally do not forget to include the taglib to use from JSP:
<%@ taglib prefix="ju" uri="/WEB-INF/tld/JsonUtils.tld"%>

No comments:

Followers