在MongoDB中使用JSON?

Sim*_*mon 18 java json mongodb

我的应用程序使用了很多JSON对象(org.json.JSONArray和朋友).将这些存储到Mongo DBObjects中的最有效方法是什么,以便可以查询它们?BasicDBObject无法序列化JSONArray - 这两个层次结构之间似乎根本没有互操作性.

小智 28

com.mongodb.util.JSON有一个方法将JSON字符串解析为DBObject.默认的JSONCallback将根据输入字符串返回BasicDBObject或BasicDBList.

Object jsonObj = ...; //any of your org.json objects
Object o = com.mongodb.util.JSON.parse(jsonObj.toString());
DBObject dbObj = (DBObject) o;
Run Code Online (Sandbox Code Playgroud)


Sim*_*mon 8

好吧,似乎没有互操作性,所以我推出了自己的.繁忙的工作来绕过类型系统:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)