MongoDB comes with “com.mongodb.util.JSON” class to convert JSON data directly to a DBObject. For example, data represent in JSON format :

{
	'name' : 'mkyong',
	'age' : 30
}

To convert it to DBObject, you can code like this :

DBObject dbObject = (DBObject) JSON.parse("{'name':'mkyong', 'age':30}");
Example

See a full example to convert above JSON data to a DBObject, and save it into MongoDB.

package com.mkyong.core;
 
import java.net.UnknownHostException;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.util.JSON;
 
/**
 * Java MongoDB : Convert JSON data to DBObject
 * 
 */
 
public class App {
	public static void main(String[] args) {
 
		try {
 
			Mongo mongo = new Mongo("localhost", 27017);
			DB db = mongo.getDB("yourdb");
			DBCollection collection = db.getCollection("dummyColl");
 
			// convert JSON to DBObject directly
			DBObject dbObject = (DBObject) JSON
					.parse("{'name':'mkyong', 'age':30}");
 
			collection.insert(dbObject);
 
			DBCursor cursorDoc = collection.find();
			while (cursorDoc.hasNext()) {
				System.out.println(cursorDoc.next());
			}
 
			System.out.println("Done");
 
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (MongoException e) {
			e.printStackTrace();
		}
	}
}

Output

{ "_id" : { "$oid" : "4dc9ebb5237f275c2fe4959f"} , "name" : "mkyong" , "age" : 30}
Done
Tags :
< PreviousNext >
MongoDB : couldn’t open /data/db/yourdb.ns errno:13 Permission deniedIndexJava MongoDB : Get collection from database
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.
My website mkyong.com is hosted by Liquid Web, I really like their fast and helpful support, it saved me a lot of time. Furthermore, their servers are extremely reliable, fast and stable, I don't remember when was the last time we had server downtime. Btw, they're offering $100 Coupon now, if you are sourcing for great hosting provider, go grab it.

Related Posts

Popular Posts