jjmartinez
jjmartinez

Reputation: 807

How to parse a BasicDBObject into other object

I'm developing a Java application using MongoDB and Java-driver.

I need to parse a BasicDBObject into an own object of my code, and I don't know if there is a way to develop automatically.

Is it possible to parse from BasicDBObject to JSON String? Then, I could parse from JSON String to my own Object, for example with GSON library. Something like

    BasicDBObject object;
    String myJSONString = object.toString();
    Gson gson = new Gson();
    MyOwnObject myObject = gson.fromJson(myJSONString, MyOwnObject.class);

And I don't want to add complex to my code, also I don't to add more extern libraries. I don't want to add Gson library or other.

Any ideas?? Is it possible to do this without external libraries?? Thanks!!

Upvotes: 0

Views: 1479

Answers (3)

jjmartinez
jjmartinez

Reputation: 807

This is the correct answer to my question

From http://docs.mongodb.org/ecosystem/tutorial/use-java-dbobject-to-perform-saves/

For example, suppose one had a class called Tweet that they wanted to save:

public class Tweet implements DBObject {
    /* ... */
}

Then you can say:

Tweet myTweet = new Tweet();
myTweet.put("user", userId);
myTweet.put("message", msg);
myTweet.put("date", new Date());

collection.insert(myTweet);

When a document is retrieved from the database, it is automatically converted to a DBObject. To convert it to an instance of your class, use DBCollection.setObjectClass():

collection.setObjectClass(Tweet.class);

Tweet myTweet = (Tweet)collection.findOne();

If for some reason you wanted to change the message you can simply take that tweet and save it back after updating the field.

Tweet myTweet = (Tweet)collection.findOne();
myTweet.put("message", newMsg);

collection.save(myTweet);

Upvotes: 0

injecteer
injecteer

Reputation: 20707

You could either use Groovy with gmongo library for that, there you have lots of handy tools for such casting.

If the language change is not an option for you, write your own reflection-based mapper. If you POJO is simple enough, the mapper shall be pretty simple.

Upvotes: 1

Smutje
Smutje

Reputation: 18173

You could have taken a look at the API: Just call object#toString() (http://api.mongodb.org/java/2.0/com/mongodb/BasicDBObject.html#toString()).

Upvotes: 1

Related Questions