Deserializing MongoDB BSON

核能气质少年 提交于 2019-12-05 16:35:58

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();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!