Search code examples
javamongodbdbobject

Convert DBObject to a POJO using MongoDB Java Driver


MongoDB seems to return BSON/JSON objects.

I thought that surely you'd be able to retrieve values as Strings, ints etc. which can then be saved as POJO.

I have a DBObject (instantiated as a BasicDBObject) as a result of iterating over a list ... (cur.next()).

Is the only way (other than using some sort of persistence framework) to get the data into a POJO to use a JSON serlialiser/deserialiser?

My method looks like this:

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;
    }

EDIT: It's pretty obvious, just do something like this.


Solution

  • There is a few java libs that can help you with it: