2

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.

5
  • 1
    Is there any particular reason why you're using the sql date object?
    – akourt
    Apr 7, 2019 at 13:02
  • 1
    Not knowing Genson, all other things being equal you should not use java.sql.Date. That class is poorly designed and long outdated. Instead use LocalDate from java.time, the modern Java date and time API.
    – Anonymous
    Apr 7, 2019 at 13:29
  • 1
    The java.sql.Date class was replaced years ago by java.time.LocalDate. See if Genson supports the java.time classes (JSR 310) built into Java 8 and later. Apr 7, 2019 at 16:52
  • 1
    Yes, I actually tried LocalDate before switching over to java.sql.Date. And it doesn't work with Genson as there are no public constructors it can call to initialize the object. Apr 7, 2019 at 17:34
  • @AlfaKhrisna take a look at the docs there are plenty of examples and explanations on how to register custom converters. Also the latest release does come with a bundle for java.time.
    – eugen
    Apr 18, 2019 at 18:23

1 Answer 1

1

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:

import java.sql.Date;
import lombok.Getter;
import lombok.Setter;

public class CrashTestDummy {
    @Getter @Setter private String name;
    @Getter @Setter private Date sqlDate;

    /** Default no-arg constructor */
    public CrashTestDummy() {
    }
}

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.

import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.junit.Test;
import com.owlike.genson.Context;
import com.owlike.genson.Converter;
import com.owlike.genson.Genson;
import com.owlike.genson.GensonBuilder;
import com.owlike.genson.stream.ObjectReader;
import com.owlike.genson.stream.ObjectWriter;

    @Test
    public void serialiseDate() throws ParseException {
        // create a converter for java.sql.Date
        Converter<Date> converter = new Converter<Date>() {
            @Override
            public void serialize(Date obj, ObjectWriter writer, Context ctx) throws Exception {
                // java.sql.Date doesn't support any time fields, so we can just focus on y, M and d
                if(obj == null) {
                    writer.writeNull();
                    return;
                }
                writer.writeValue(  obj.getTime() );
            }

            @Override
            public Date deserialize(ObjectReader reader, Context ctx) {
                Long value = reader.valueAsLong();
                Date sqlDate = new java.sql.Date( value );
                return sqlDate;
            }
        };

        // Build a new Genson object with our converter
        Genson genson = new GensonBuilder()
                .setSkipNull(true)
                .withConverter(converter, java.sql.Date.class)
                .create();

        // make an important SQL date for testing
        java.util.Date utilDate = new SimpleDateFormat("dd MMM yyyy").parse("30 July 1966");
        Date sqlDate = new Date(utilDate.getTime() );

        // Make something to serialise
        CrashTestDummy original = new CrashTestDummy();
        original.setName( "Alfa Khrisna" );
        original.setSqlDate( sqlDate );

        // Call Genson as usual
        String json = genson.serialize( original );
        System.out.println( json );

        // Deserialise as usual; for brevity I'm comparing dates in millis since epoch.
        CrashTestDummy clone = genson.deserialize(json, CrashTestDummy.class);
        assertEquals(new SimpleDateFormat("dd MMM yyyy").parse("30 July 1966").getTime(), clone.getSqlDate().getTime());
        assertEquals("Alfa Khrisna", clone.getName());
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.