I am working on a Java servlet and I need to serialize and deserialize a class into JSON and back. To do this, I am using the Genson library, but I am hitting a snag.
Genson fails at deserializing instances of the Date class (java.sql.Date)
I have tried setting custom date formatters, but they don't seem to affect deserialization.
I have also tried to plug in new converters using the builder call withConverter(), but I can't figure out how the parameters work.
Here is my builder call for the moment
Genson genson = builder.setSkipNull(true).create();
The class I am serializing has a field of type Date
private Date introDate;
This is a snippet of the stack trace that occurs if I try to deserialize the produced JSON
Caused by: com.owlike.genson.JsonBindingException: Could not access value of property named 'hours' using accessor public int java.sql.Date.getHours() from class java.sql.Date
at com.owlike.genson.reflect.PropertyAccessor.couldNotAccess(PropertyAccessor.java:40)
at com.owlike.genson.reflect.PropertyAccessor$MethodAccessor.access(PropertyAccessor.java:70)
at com.owlike.genson.reflect.PropertyAccessor.serialize(PropertyAccessor.java:24)
at com.owlike.genson.reflect.BeanDescriptor.serialize(BeanDescriptor.java:92)
at com.owlike.genson.convert.NullConverterFactory$NullConverterWrapper.serialize(NullConverterFactory.java:69)
at com.owlike.genson.reflect.PropertyAccessor.serialize(PropertyAccessor.java:27)
... 38 more
The problem here is that methods like getHours() are deprecated, thus calling them produces an IllegalArgumentException. I do not know how to get around this for the moment.
You could use java.util.Date. That works with Genson.
If we're sticking with java.sql.Date, then you can write your own converter and make Genson use that.
Let's start with an object to ser/deser:
Then we can tell Genson to use a custom converter. In this case I'm converting it to a Long in epoch time and back again. You might decide to use a specific date format instead.