Ben Siver
Ben Siver

Reputation: 2948

Deserializing MongoDB BSON

I attempting to take a response from a REST service that queries an instance of MongoDB and parse the response into a Java object. The web service returns the response with a MIME type of html with a newline character separating each record that is returned (although I have the ability to adjust what the service returns). What is the easiest/most efficient way for converting the BSON response into a Java object? I have already created a template class in Java to store the data.

Thanks in advance!

edit: A colleague suggested to me using the MongoDB Java driver's BSON parsing utilities in the webservice itself and then returning a nicely formatted HTML string. This still leaves me with parsing to do in my application, but will function as a workaround for the time being. Still looking for a way to easily deserialize the BSON response to a Java object.

Upvotes: 4

Views: 9353

Answers (1)

Ben Siver
Ben Siver

Reputation: 2948

For those interested, I found the solution to my problem. It turns out that the BSON format can be parsed just like JSON using Google's GSON driver. The one tricky part that I had to deal with was figuring a way to store nested fields in my template class. The way to allow GSON to parse nested documents is to declare static inner classes in your template class. Here is an example:

public BSONObject {
   // Private fields
   private int foo;
   private String bar;

  // Constructors
  public BSONObject() {}

  // Static inner subclasses
  private Widget widget;
  private Duck quack;

  // Getters & Setters for outer class
  public int getFoo() {...}
  public String getBar() {...}
  public Widget getWidget() {...}
  public Duck getDuck() {...}

  // Static inner class declarations
  public static Widget {
     // include vars & getters/setters
  }

etc.

Declaring the template class following the above framework allowed me to easily parse MongoDB's formatting using a few lines of code from the GSON library. Please note that I concatenated a "\n" to each entry when returning data from my webservice so as to separate each document in Mongo's BSON response:

public String getNestedField() {
   Gson gson = new Gson();
   String [] split = response.split("\n");
   JsonParser p = new JsonParser();
   String json = split[0];
   BSONObject b = gson.fromJson(p.parse(json), BSONObject.class);
   return b.getWidget().getField();
}

Upvotes: 1

Related Questions