3

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?

1 Answers1

2

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);
Community
  • 1
  • 1
Fabian
  • 3,310
  • 3
  • 26
  • 35