Saturday, September 20, 2014

Jackson JSON parser - Writing Custom Deserializer

One of major difference between Jackson and GSON is how they handle json parsing and mapping the json to a class object. While doing so Jackson uses strict checking which means the object from which the json was created and the class to which the json has to be mapped should be in strict sync.

Consider the following example -

class Foo {
    private String value;
}
class Bar {
    private String value;
}
and

String json = "{\"value\" : \"whatever\"}";
new Gson().fromJson(json, Foo.class);
new Gson().fromJson(json, Bar.class);
Gson is setup to perform a best effort to deserialize the given JSON into an instance of the given class. It will map as many fields as it finds. If none are found, that's too bad, mapping will not be done.

Coming to the custom deserializer thing. We may need to write one in few cases as - changing date format of the json string to our custom one. For writing our custom deserializer we need to write a class which extends JsonDeserializer<T>. In this class we implement  the method deserialize(...) which contains our custom conversion code.

public class CustomJsonDateDeserializer extends JsonDeserializer<Date> {
@Override
public Date deserialize(JsonParser jsonParser, DeserializationContext context)
        throws IOException, JsonProcessingException {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm a z");
    String date = jsonParser.getText();
    try {
        return format.parse(date);
    } catch (ParseException e) {
        throw new RuntimeException(e);
    }
  }
}

Now annotate the field in the POJO which has to be deserialized using the custom deserializer.

@JsonDeserialize(using = CustomJsonDateDeserializer.class) private Date createdAt;

That's it. Pretty simple thing.

0 comments:

Post a Comment