/** * Cast an object according to its instance * * @param value the object to transform * @return the BSON object */ public static Object valueToBson(Object value) { if (value instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) value; return fieldMapToBson(map); } else if (value instanceof List) { @SuppressWarnings("unchecked") List<Object> values = (List<Object>) value; return listToBson(values); } else if (value instanceof Object[]) { return listToBson(Arrays.asList((Object[]) value)); } else { return serializableToBson(value); } }
protected static List<Object> listToBson(List<Object> values) { List<Object> objects = new ArrayList<>(values.size()); for (Object value : values) { objects.add(valueToBson(value)); } return objects; }
for (Object o : list) { if (o != null) { klass = scalarToSerializableClass(o.getClass()); break; List<Serializable> l = new ArrayList<>(list.size()); for (Object o : list) { l.add((Serializable) bsonToFieldMap((Document) o)); int i = 0; for (Object o : list) { array[i++] = scalarToSerializable(o); return (Serializable) bsonToFieldMap((Document) value); } else { return scalarToSerializable(value);
/** * Create a BSON object with a single field from a pair key/value * * @param key the key which corresponds to the field id in the object * @param value the value which corresponds to the field value in the object * @return the new BSON object */ public static Document fieldMapToBson(String key, Object value) { return fieldMapToBson(Collections.singletonMap(key, value)); }
/** * Create a map from a BSON object * * @param doc the BSON object to parse * @return the new map */ public static Map<String, Object> bsonToFieldMap(Document doc) { Map<String, Object> fieldMap = new HashMap<>(); for (String key : doc.keySet()) { if (MONGODB_ID.equals(key)) { // skip native id continue; } fieldMap.put(key, bsonToValue(doc.get(key))); } return fieldMap; }
/** * Create a BSON object from a map * * @param fieldMap a map of keys/values * @return the new BSON object */ public static Document fieldMapToBson(Map<String, Object> fieldMap) { Document doc = new Document(); for (Map.Entry<String, Object> entry : fieldMap.entrySet()) { Object val = valueToBson(entry.getValue()); if (val != null) { doc.put(entry.getKey(), val); } } return doc; }