What are the ways of converting a Java object to a MongoDB document and vice versa?

Asked 11-Mar-2018
Viewed 892 times

0

What are the ways of converting a Java object to a MongoDB document and vice versa?



1 Answer


0

"Converting Java Object to MongoDB document"
Generally, MongoDB document uses JSON for converting your Java Object (POJO) to JSON document and use it in MongoDB.
You can use Gson library to convert your Java Object(POJO) to JSON

Converting POJO(Plain Old Java Object) to MongoDB Document
  •  Firstly, Create Gson object
            Gson gson=new Gson();
  • Convert Your Java Object to JSON
        String json = gson.toJson(POJO);
  • Add the following code in your project.
 FileWriter writerObj = new FileWriter("file.json");
   writerObj.write(json);
   writerObj.close();

Converting MongoDB Document back to Java Object(POJO) :
  •  Firstly, Create Gson object
        Gson gson=new Gson();

  •  Convert it back to Java Object (POJO)
BufferedReader br = new BufferedReader(new FileReader("file.json"));
 Data POJO = gson.fromJson(br,POJO.class);
   System.out.println(POJO);