{
'name' : 'mongodbwise',
'age' : 30
}
Para convertê-lo para DBOBJECT, você pode codificar assim:
DBObject dbObject = (DBObject) JSON.parse("{'name':'mongodbwise', 'age':30}");
Exemplo
Veja um exemplo completo para converter acima dados JSON para um DBOBJECT e salve-o no MongoDB.
package com.mongodbwise.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':'mongodbwise', '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" : "mongodbwise" , "age" : 30}
0 comentários:
Postar um comentário