开发者

Using JSON with MongoDB?

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 JSO开发者_StackOverflow中文版NArray--there seems to be no interoperability between these two hierarchies at all.


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;
        }
    }
}


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜