converting Document objects in MongoDB 3 to POJOS

后端 未结 4 951
攒了一身酷
攒了一身酷 2020-12-11 01:36

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         


        
4条回答
  •  伪装坚强ぢ
    2020-12-11 02:11

    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().

提交回复
热议问题