Searching...
Tuesday, 18 September 2012

Java Mongodb Convert JSON Data To DBObject Example

23:42

·         Create a Maven project and add below dependency in pom.xml


              <dependency>
                     <groupId>org.mongodb</groupId>
                     <artifactId>mongo-java-driver</artifactId>
                     <version>2.5.2</version>
              </dependency>

·         Create a Java class to convert JSON Data To DBObject


package com.pretechsol;

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;

public class PretechJSONDBObjectConverstion {

   /**
    * @param args
    */
   public static void main(String[] args) {
          try {

                 Mongo mongo = new Mongo("localhost", 27017);
                 DB db = mongo.getDB("pretechdbTest");
                 DBCollection collection = db.getCollection("pretechDocument");

                 // convert JSON to DBObject directly
                 DBObject dbObject = (DBObject) JSON
                               .parse("{'name':'pretech', 'address':'Bangalore'}");

                 collection.insert(dbObject);

                 DBCursor cursorDoc = collection.find();
                 while(cursorDoc.hasNext()) {
                        System.out.println(cursorDoc.next());
                 }

                 System.out.println("Parsing completed");

          } catch(UnknownHostException e) {
                 e.printStackTrace();
          } catch (MongoException e) {
                 e.printStackTrace();
          }
   }
}

·         Output


{ "_id" : { "$oid" : "502fc9c9c342ea4c65907052"} , "name" : "pretech" , "address" : "Bangalore"}
{ "_id" : { "$oid" : "50596856efa3288bdd9dcc30"} , "name" : "pretech" , "address" : "Bangalore"}
Parsing completed

0 comments: