Monday, May 25, 2015

JSON Jackson custom deserializer to return empty String instead of null

Needed a way to deserialize null values in a JSON as emptry strings (""). This is the shortest I could come with.
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.UntypedObjectDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;

public class NullHandlerDeserializer extends UntypedObjectDeserializer {

  private static final long serialVersionUID = 1L;

  public Object deserialize(JsonParser jp, DeserializationContext ctxt)
    throws IOException {
    switch (jp.getCurrentToken()) {
     case VALUE_NULL:      
      return "";
      return super.deserialize(jp, ctxt);

The class extends from an existing deserializer implementation to avoid having to code the handling of all JSON tokens. I needed to worry only about VALUE_NULL token.

And to configure the custom deserializer in the ObjectMapper:

ObjectMapper om = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Object.class, new NullHandlerDeserializer());

Wednesday, May 20, 2015

XSLT Learnings

Just listing some XSLT learnings from a recent project where I had to learn from scratch.

Basic shelling:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet xmlns:xsl="" version="2.0">
<xsl:output method="xml" encoding="utf-8" indent="no"/> 
<xsl:template match="/">
    <!-- XSL stuff -->

Converting a list of states from XML to HTML select input options:

Given an input like this:


Use XSL like this:

<select name="states">
    <xsl:for-each select="states/*">
             <xsl:attribute name="value"><xsl:value-of select="name(.)"/></xsl:attribute>
        <xsl:value-of select="string(.)"/>

To get this:

        <option value="AL">Alabama</option>
        <option value="AK">Alaska</option>
        <option value="AR">Arkansas</option>
        <option value="CA">California</option>
        <option value="CO">Colorado</option>

Some few things to note:

  • "name(.)" gives you the element (tag) name.
  • "string(.)" gives you the element value (what is between opening and closong tags).

Checking element has children or content

<xsl:if test="some/element-tag/text() != ''">