Monthly Archives: April 2011

File Naming Conventions

Dilbert - File Naming Conventions

Dilbert - File Naming Conventions

The sad thing is that I have actually been on a “committee” like this in the past where people obsessed over naming conventions.

Meet Ruby

I am very excited to announce that we added a new member to the family today. Meet Ruby:

Ruby

Ruby

Ruby is roughly three years old and some combination of Lab and Beagle according to the shelter we adopted her from.

So far I don’t think we could have hoped for a better choice of dogs. Ruby is sweet, playful, and very social. So social she climbed right up on my chest for an afternoon nap. Unfortunately for me she weighs in at a stout 61 pounds which made breathing a bit of a challenge.

Admittedly our cats are less than thrilled about their new housemate but hopefully in the next few days they will learn to ignore the dog and get back to their normal routine.

Greatest. Comic. Ever.

Dilbert.com

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:

@Override
public JsonElement serialize(ObjectId id, Type typeOfT,
   JsonSerializationContext context)
{
   JsonObject jo = new JsonObject();
   jo.addProperty("$oid", id.toStringMongod());
   return jo;
}
@Override
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.