Tag Archives: Java

De/serializing MongoDB IDs and Dates with GSON

I recently ran into a need to serialize and deserialize MongoDB Object ID’s and dates due to the manner in which the application I am working on is  using Google’s GSON library to convert data retrieved from MongoDB into POJOs.

If you rely on the built in type adapters the come with the GSON library for serialization the library will convert Object IDs from their JSON representation of {“$oid” : “4c2209f9f3924d31102bd84a”} into a plain old string (i.e. “4c2209f9f3924d31102bd84a”) when what you probably want is to serialize the value as a BSON ObjectId. The GSON library also does a poor job of serializing MongoDB’s “yyyy-MM-dd’T’HH:mm:sss’Z'” date format. Fortunately this behavior can be over ridden through the use of custom serializers and deserializers. Unfortunately I could not find any good examples of how to write custom serialization code for MongoDB online so I spent a good deal of time figuring it out through trial and error (and some help from my boss).

Below is a sample of how to serialize and deserialize the ObjectId:

public JsonElement serialize(ObjectId id, Type typeOfT,
   JsonSerializationContext context)
   JsonObject jo = new JsonObject();
   jo.addProperty("$oid", id.toStringMongod());
   return jo;
public ObjectId deserialize(JsonElement json, Type typeOfT,
   JsonDeserializationContext context) throws JsonParseException
   try {return new ObjectId(json.getAsJsonObject()
       .get("$oid").getAsString()); }
   catch (Exception e) { return null; }

Note: The full source of the GsonTypeAdapter class can be found here:  GsonTypeAdapter.txt. Please note that this code handles both MongoDB ObjectIDs and dates but it has not been optimized yet. Use it at your own risk and feel free to leave comments/critiques attached to this post.

Note 2: I wrote this code as part of my day job at IKANOW where we are doing some very cool things in the knowledge discovery and analysis space.