How To Use GSON To Parse Dates for MongoDB

image
Rodrigo Asensio 7 years ago

1 min read

How to use GSON to convert Date objects to mongo''s date format in Java


  

Working with MongoDB is really cool. Is easy to setup and use any API in pretty much any programming lang out there. When you work in Java like me you will have a few challenges. First of all what I hate from Java and love from NodeJS is the dynamic creation of objects using directly JSON. This is also a nice ability of C#. Now when you need to serialize java objects to JSON to transform into data objects for the Mongo driver you will find GSON (google json parser) really useful but one of the problems will be that one of the types will be transformed to string, not to the type you really want inside Mongo. Dates.

So the solution for this case if you don’t use Spring Data Mongo or Morphia is to create and register a GSON converter with this code.

private static final String MONGO_UTC_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";

public JsonElement serialize(Date src, Type type, JsonSerializationContext context) {
  if (src == null) {
    return null;
  } else {
    SimpleDateFormat format = new SimpleDateFormat(MONGO_DATE_FORMAT);
    JsonObject jo = new JsonObject();
    jo.addProperty("$date", format.format(src));
    return jo;
  }
}
@Override
public Date deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
  Date date = null;
  SimpleDateFormat format = new SimpleDateFormat(MONGO_DATE_FORMAT);
    try {
      date = format.parse(json.getAsJsonObject().get("$date").getAsString());
    } catch (ParseException e) {
      date = null;
    }
  return date;
}

image

Rodrigo Asensio

Rodrigo Asensio is Manager of Solution Architecture at Amazon Web Services. He has more than 20 years of experience designing and operating distributed solutions. He is currently responsible for a team in the Enterprise segment helping large clients accelerate their adoption of the cloud and optimize the utilization of their resources.

Check out all articles