Main Tutorials

Java MongoDB : Convert JSON data to DBObject

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

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
18 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
danny
9 years ago

its not working if the parse parameters have moe than 1 documents.
parse(“{‘name’:’mkyong’, ‘age’:30},{‘name’:’mkyong1′, ‘age’:31}”);

Syed
6 years ago
Reply to  danny

To parse more than 1 document, use [ ]
parse(“[{‘name’:’mkyong’, ‘age’:30},{‘name’:’mkyong1?, ‘age’:31}]”);

Vaibhav Srivastav
4 years ago

Do we need to close DBCursor after process complete
DBCursor cursorDoc =
cursorDoc.close()

Hua Chen
7 years ago

How to parse a date json into org.bson.Document?

Drashti Pandya
8 years ago

How can I add textField.getText() data in mongoDb

Daniela Marques De Morais
8 years ago

Wow thanks

Tonyq Wang
10 years ago

I write another solution for this. To convert the json to BasicDBObject with a code generator.
http://tonyq.org/json2Bo/index.html

Deepak
10 years ago

The article was very helpful to me. Thank you!

10 years ago

I have a question, please reply.
Thanks in advance.

While parsing the the JSON like in
DBObject dbObject = (DBObject)JSON.parse(“{name:’mkyong’, age:30}”);

We are just simply giving the string directly. I mean we are hard coding the input text.

I am trying to parameterize this thing, and I cannot get how to store a string variable instead of hardcoding it directly.

For Example,
my String is ;
String myString = “Hello World”;
I wish to store this myString instead of hardcoding the “Hello World” value directly..

Can you please help me?

Thank you.

Thamizharasu
10 years ago

Hi,
You have to pass the string which has the value and construct the JSON string using StringBuilder. Then pass the JSON string the method. It will work.

Thanks,
Tham

Leonardo Pinto
10 years ago

The snippet

{
    "_id" : { "$oid" , "4dc9ebb5237f275c2fe4959f"}
}

saved my day! (im using NoSQLUnit for integration tests)

thx a lot!

mandarabnave
10 years ago
Reply to  Leonardo Pinto

I have a question, please reply.
Thanks in advance.

While parsing the the JSON like in
DBObject dbObject = (DBObject)JSON.parse(“{name:’mkyong’, age:30}”);

We are just simply giving the string directly. I mean we are hard coding the input text.

I am trying to parameterize this thing, and I cannot get how to store a string variable instead of hardcoding it directly.

For Example,
my String is ;
String myString = “Hello World”;
I wish to store this myString instead of hardcoding the “Hello World” value directly..

Can you please help me?

Thank you.

Ajith
11 years ago

Nice article !!
When I try importing a date using the above function

{
	'name' : 'mkyong',
	'age' : 30,
        'DOB' : 2000-12-12
}

The datatype by default is taken as string. How do I import dates directly from JSON ?

Any idea ?

Regds
AN

armen
11 years ago

Hello. I have following method, I want find by id from table and get Book object

public Book getBookObject(Long bookId)
{
Book book = new Book();

BasicDBObject query = new BasicDBObject();

query.put(“bookId”, bookId);

DBCursor cursor = bookCollection.find(query);

try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close(); }

return book;
}

How can I assign cursor.next() result to my Book object?
@Model
public class Book
{

private Long bookId;
@Size(min = 1, max = 20)
private String name;
@Size(min = 1, max = 20)
private String author;
@Size(min = 1, max = 20)
private String language;
private int year;
///
After fin I get JSON object
INFO: { “_id” : { “$oid” : “50125127478556057fb20600”} , “bookId” : 18 , “name” : “Java one” , “year” : 11969 , “language” : “255” , “author” : “5858”} and so? I need show it in the web page and update the document. Help

Martina
11 years ago

How can I convert from DBobject back to a java Object? With MappingMongoConverter? I can’t figure out the MappingContext argument to construct that converter.

KiranRamannaIyer
8 years ago
Reply to  Martina

I am also Waiting for answer to this query…

Silvio Rainoldi
9 years ago
Reply to  Martina

Need this too… Did you find a solution after 3 years? 😛

msangel
12 years ago

Can I save not strict JSON as Object in this DB?
For example:

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

This code cause exception, but if to work with another tool for mongo – DB allow to save this objects.
Why java api not allow this and how can i solse this problem?