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.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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;
回答2:
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;
}
}
}
回答3:
i don't know about java mongo driver, but in c# mongo driver has BsonSerializer class. You can use it like following code:
var q = BsonSerializer.Deserialize<MyDocument>("{ jsonValueName:jsonValue }");
plz check mongo-java-driver, i thank it should contain the same facilities
also look at bson4jackson
回答4:
This works, and throws the question as to why the Mongo folks decided to have an Object return type instead of a DBObject: does anyone know?
A good alternative, if you have a lot of JSON in your app, would be to use Jackson for the (de)serialization.