SpringBoot and MongoDB Saving Issue for a JSONObject Field inside a POJO SpringBoot and MongoDB Saving Issue for a JSONObject Field inside a POJO json json

SpringBoot and MongoDB Saving Issue for a JSONObject Field inside a POJO


Here is a generic solution to store any document

package io.innoit.elearning.generic;import java.util.List;import org.bson.Document;import org.json.JSONObject;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.mongodb.core.MongoTemplate;import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.CrossOrigin;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/api/generic")@CrossOrigin(origins = { "*" })public class GenericController {    @Autowired    private MongoTemplate mongoTemplate;    @PostMapping    public ResponseEntity<Document> addData(@RequestBody String data) {        JSONObject jsonObject = new JSONObject(data);        String documentName = jsonObject.getString("documentName");        Document doc = Document.parse(data);        Document insertedDoc = mongoTemplate.insert(doc, documentName);        return new ResponseEntity<>(insertedDoc, HttpStatus.CREATED);    }    @GetMapping("/{documentName}")    public List<Document> getData(@PathVariable String documentName) {        List<Document> allData = mongoTemplate.findAll(Document.class, documentName);        return allData;    }}