Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fasterxml ObjectNode to MongoDB - Java

Hello I have some Json data in form of a com.fasterxml.jackson.databind.node.ObjectNode and I want to store it in a MongoDB.

How can the ObjectNode efficiently be converted to a MongoDB DBObject and vice versa?

like image 751
Biff Wellington Avatar asked Jun 06 '26 09:06

Biff Wellington


1 Answers

For such a simple mapping, most tools from http://json.org (section java) would work. For one of them (Jackson, http://wiki.fasterxml.com/JacksonInFiveMinutes), you'd do:

HashMap<String,Object> result = new ObjectMapper().readValue(JSON_SOURCE, HashMap.class);

(where JSON_SOURCE is a File, input stream, reader, or json content String) see: Convert Json to Map

Specifically for inserting an ObjectNode into mongodb you could do the following if you're using Java:

BasicDBObject dbObject = new BasicDBObject();
HashMap<String, Object> keyValuePairs = new ObjectMapper().readValue(TheObjectNode.traverse(), HashMap.class);
dbObject.putAll(keyValuePairs);
like image 199
Fabian Avatar answered Jun 09 '26 11:06

Fabian