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);