Monday, October 15, 2007

User defined types with JsonMarshaller

I came across the JsonMarshaller project while searching for a Java library for unmarshalling JSON. This is a nifty little framework and uses Java 5 annotations for marshalling and unmarshalling JSON.

JsonMarshaller provides simple annotations @Entity and @Value for marking up your classes for marshalling and unmarshalling. However, I wanted something more than what the base framework provides - the ability to convert dates back and forth. The framework supports a so called type option to specify a user defined type for a value. This is a cool idea for extending the basic types supported out of the box. The (simplified) code for my DateType class that solved my problem is below:



public class DateType implements Type {

@Override
public Class getReturnedClass() {
return Date.class;
}

@Override
public Object marshall(Date entity) {
SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
return format.format(entity);
}

@Override
public Date unmarshall(Object object) {
String date = (String) object;
Date d = null;
try {
d = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z").parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
return d;
}
}




This simple class can read a String representing a date in most commonly used formats and return a java.util.Date. It can also read a java.util.Date and return a String representing that date.

3 comments:

Pascal-Louis Perez said...

Hey, thanks for posting this example... I guess in time the documentation of the JsonMarshaller will e a bit more extensive.

I'd recommend using Joda time instead of the java.util.Date in your projects. The APIs of Joda are much more well thought through ;)

Unknown said...

Got me to check out JSON @ json.org.
Interesting. And a '/' is a Solidus?
quite fun if all the keys had a Latin root :-).
Cmon now, regular bloggin wont hurt! Keep it going :-)

Ram

Pascal-Louis Perez said...

Hey, thanks for this post. I'm the lead of the JsonMarshaller project (which moved recently to http://code.google.com/p/jsonmarshaller) and would like to know if you could contribute to http://code.google.com/p/jsonmarshaller/wiki/UserDefinedTypes or other pages.