Search code examples
javarestdatejerseygenson

Parse JSON Date from POST with Genson and Jersey


Quick Intro (can be skipped) : Hi, there's a lot of questions and answers about this topic, but sometimes the solution is so simple that you just don't even think about, and because I've lost a lot of time I want to post a complement to all answers.

Problem : You have a JSON REST service that handles POST requests to save a JSON object, but that object contains a Date field that is not parsed out-of-the-box by Genson.

The Java Object :

public class MyObj {

    // The field you want to serialize/deserialize
    private Date date;

    // Constructor with no arguments needed by Genson
    public MyObj() {}
}

The REST service with Jersey :

@Path("/api/my-obj")
public class MyObjAPI {

    @POST
    @Consumes("application/json")
    public Response insert(MyObj myObj) {
        // do what you want with myObj, it's ready to use with the date
        return Response.created('url/to/created/object').build();
    }
}

The client in javascript with jQuery :

// This is the JSON Object to POST
var myObj = {
    date: new Date()
};

$.ajax({
    method: 'POST',
    url: '/api/my-obj',
    data: JSON.stringify(myObj),
    dataType: 'json',
    processData: false,
    contentType: 'application/json'
});

Solution

  • SOLUTION :

    Genson provides an easy way to define how dates are (de)serialized, this is the solution you can find everywhere :

    @Provider
    public class GensonProvider implements ContextResolver<Genson> {
    
        private final Genson genson = new GensonBuilder()
                .useDateAsTimestamp(false)
                .useDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"))
                .create();
    
        @Override
        public Genson getContext(Class<?> type) {
            return genson;
        }
    }
    

    IMPORTANT :

    If the solution above is not working, be sure that the Date type of the field in your Java Object is the one imported with :

    import java.util.Date;
    

    and not :

    import java.sql.Date;
    

    I figured it out by myself, but didn't find it anywhere on StackOverflow, it's a stupid error so simple that you could not think about (like me), I hope it'll help someone.