I\'m saving an object with a java.util.Date field into a MongoDB 3.2 instance.
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsStr
I save a tag with my mongo document that specifies the original type of the object stored. I then use Gson to parse it with the name of that type. First, to create the stored Document
private static Gson gson = new Gson();
public static Document ConvertToDocument(Object rd) {
if (rd instanceof Document)
return (Document)rd;
String json = gson.toJson(rd);
Document doc = Document.parse(json);
doc.append(TYPE_FIELD, rd.getClass().getName());
return doc;
}
then to read the document back into the Java,
public static Object ConvertFromDocument(Document doc) throws CAAException {
String clazzName = doc.getString(TYPE_FIELD);
if (clazzName == null)
throw new RuntimeException("Document was not stored in the DB or got stored without becing created by itemToStoredDocument()");
Class> clazz;
try {
clazz = (Class>) Class.forName(clazzName);
} catch (ClassNotFoundException e) {
throw new CAAException("Could not load class " + clazzName, e);
}
json = com.mongodb.util.JSON.serialize(doc);
return gson.fromJson(json, clazz);
}
Thanks to Aleksey for pointing out JSON.serialize().