My application uses JSON objects a lot (org.json.JSONArray and friends). What's the most efficient way to store these into Mongo DBObjects so they can be queried? BasicDBObject can't serialize a JSONArray--there seems to be no interoperability between these two hierarchies at all.
The process to import JSON into MongoDB depends on the operating system and the programming language you are using. However, the key to importing is to access the MongoDB database and parsing the file that you want to import. You can then go through each document sequentially and insert into MongoDB.
JSON document databases are a good solution for online profiles in which different users provide different types of information. Using a JSON document database, you can store each user's profile efficiently by storing only the attributes that are specific to each user.
A JSON database is arguably the most popular category in the NoSQL family of databases. NoSQL database management differs from traditional relational databases that struggle to store data outside of columns and rows.
com.mongodb.util.JSON has a method to parse a JSON string into DBObject. The default JSONCallback will return a BasicDBObject or BasicDBList according to input string.
Object jsonObj = ...; //any of your org.json objects
Object o = com.mongodb.util.JSON.parse(jsonObj.toString());
DBObject dbObj = (DBObject) o;
OK it seems there is no interoperability, so I rolled my own. Busywork to get around the type system:
public class Util {
public static DBObject encode(JSONArray a) {
BasicDBList result = new BasicDBList();
try {
for (int i = 0; i < a.length(); ++i) {
Object o = a.get(i);
if (o instanceof JSONObject) {
result.add(encode((JSONObject)o));
} else if (o instanceof JSONArray) {
result.add(encode((JSONArray)o));
} else {
result.add(o);
}
}
return result;
} catch (JSONException je) {
return null;
}
}
public static DBObject encode(JSONObject o) {
BasicDBObject result = new BasicDBObject();
try {
Iterator i = o.keys();
while (i.hasNext()) {
String k = (String)i.next();
Object v = o.get(k);
if (v instanceof JSONArray) {
result.put(k, encode((JSONArray)v));
} else if (v instanceof JSONObject) {
result.put(k, encode((JSONObject)v));
} else {
result.put(k, v);
}
}
return result;
} catch (JSONException je) {
return null;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With