Using JSON with MongoDB?

前端 未结 4 398
南旧
南旧 2020-12-13 15:18

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? BasicDBOb

相关标签:
4条回答
  • 2020-12-13 15:26

    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 讨论(0)
  • 2020-12-13 15:27

    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

    0 讨论(0)
  • 2020-12-13 15:46

    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;
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-13 15:50

    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;
    
    0 讨论(0)
提交回复
热议问题