在MongoDB中使用JSON? [英] Using JSON with MongoDB?

查看:551
本文介绍了在MongoDB中使用JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

好像好像没有互操作性,所以我自己动手了。绕过类型系统的繁忙工作:

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

这篇关于在MongoDB中使用JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆