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;

  @Override
  public Object deserialize(JsonParser jp, DeserializationContext ctxt)
    throws IOException {
    switch (jp.getCurrentToken()) {
     case VALUE_NULL:      
      return "";
     default: 
      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());
om.registerModule(module);

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="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" encoding="utf-8" indent="no"/> 
<xsl:template match="/">
    <!-- XSL stuff -->
</xsl:template>
</xsl:stylesheet>

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

Given an input like this:

<states>
    <AL>Alabama</AL>
    <AK>Alaska</AK>
    <AR>Arkansas</AR>
    <CA>California</CA>
    <CO>Colorado</CO>
</states>

Use XSL like this:

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

To get this:

<select>
        <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>
</select>

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() != ''">
...
</xsl:if>