Thursday, June 7, 2012

Convert JSON to DBObject

Conversion of JSON to DBObject need JSON parsing only here I attach the simple
code to understand it.
package com.test;

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 ConvertJSON2DBObject {
 public static void main(String[] args) {
  try {
   Mongo mongo = new Mongo("localhost",27017);
   DB db = mongo.getDB("myDBName");
   DBCollection collection = db.getCollection("myCollectionName");
   
   //convert JSON to DBObject
   DBObject dbObject = (DBObject) JSON.parse("{'empName':'Rajkumar Singh','emppId':62990}");
   collection.insert(dbObject);
   
   DBCursor cursor = collection.find();
   
   while(cursor.hasNext()){
    System.out.println("OBJ IS : "+cursor.next());
   }
  } catch (UnknownHostException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (MongoException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  
 }

}


Post a Comment