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

0 votes
155 views
simron shukla asked 11-Mar-2018 in programming by simron shukla
What are the ways of converting a Java object to a MongoDB document and vice versa?


1 Answer

0 votes
Arti Mishra answered 10-Jul-2018 by Arti Mishra
"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);