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 ClassgetReturnedClass() {
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:
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 ;)
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
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.
Post a Comment