2011-10-07 88 views
15

MongoDB似乎返回BSON/JSON对象。使用MongoDB Java驱动程序将DBObject转换为POJO

我认为你肯定能够检索值作为字符串,整数等,然后可以保存为POJO。

我有一个DBObject(实例化为BasicDBObject)作为遍历列表的结果...(cur.next())。

使用JSON serlialiser/deserialiser来获取数据到POJO的唯一方法(除了使用某种持久性框架)?

我的方法是这样的:

public List<User> findByEmail(String email){ 
     DBCollection userColl; 
     try { 
      userColl = Dao.getDB().getCollection("users"); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace();} 
      DBCursor cur = userColl.find(); 
      List<User> usersWithMatchEmail = new ArrayList<User>(); 

      while(cur.hasNext()) { 
       // this is where I want to convert cur.next() into a <User> POJO 
       usersWithMatchEmail.add(cur.next()); 
      } 
     return null; 
    } 

编辑:这是很明显的,只是做这样的事情。

+0

愚蠢的我,你可以调用get()上DBOBJECT和获得的价值。我会发布代码。 – Ankur

回答

9

有几个的Java库,可以帮助你用它:

+0

谢谢,现在我试图学习Java API,但最终会使用其中的一种。 – Ankur

+0

为spring-data-mongodb +1,它的奇妙。有注释来指定文档ID,字段名称,文档引用;请注意,不支持级联保存:http://static.springsource.org/spring-data/data-mongodb/docs/current/reference/html/#mapping-usage-references –

+1

@AndrewB可以弹出数据mongodb be在EJB项目中使用?这是明智的做法吗?因为我的其余项目对Spring没有任何依赖! – Nikhil

3

您可以使用谷歌提供的GSON库。这是它的example。还有很多其他的api可以用来将json转换成pojo,比如jettision api等。

39

让Spring做它已经为此建立了东西繁重......

真正的窍门是:mongoTemplate.getConverter()读取(让Foo.class,OBJ)。

例如,使用DBCursor时 -

while (cursor.hasNext()) { 
    DBObject obj = cursor.next(); 
    Foo foo = mongoTemplate.getConverter().read(Foo.class, obj); 
    returnList.add(foo); 
} 

http://revelfire.com/spring-data-mongodb-convert-from-raw-query-dbobject/

+0

非常感谢您的支持。为了快速入门,maven依赖项是:org.springframework.data/spring-data-mongodb/1.3.2.RELEASE – vikingsteve

+0

完美地工作 – cheloncio

+0

你值得一个cookie:D –

6

虽然后期的答案,有人可能会发现这很有用。

我用GSON从BasicDBObject转换成我自己的POJO这是TinyBlogDBObject

TinyBlogDBObject obj = convertJSONToPojo(cursor.next().toString()); 

private static TinyBlogDBObject convertJSONToPojo(String json){ 

    Type type = new TypeToken<TinyBlogDBObject>(){}.getType(); 

    return new Gson().fromJson(json, type); 

} 
+1

这是行不通的,因为ID以{“_id”:{“$ oid”:xxxx}}和gson抱怨的形式返回。您需要手动将其转换为字符串或替换jsonobject中的值。 – arisalexis

+0

或者你可以首先提供你自己的_id值作为字符串,并避免这样的问题。 –