How can I store raw JSON in Mongo using Spring Boot

I want to use an HTTP PUT request with JSON and store it unmodified in Mongo. How can i do this? The best I have:

@RestController
public class ConfigurationController {

    @Autowired
    private MongoTemplate mongoTemplate;

    @RequestMapping
    public DBObject index() {
        return mongoTemplate.getCollection("foo").findOne();
    }

    @RequestMapping(method = RequestMethod.PUT)
    ResponseEntity<?> add(@RequestBody DBObject object) {

        mongoTemplate.insert(object, "foo");

        return new ResponseEntity<>(null, HttpStatus.CREATED);
    }

}
+9
source share
5 answers

In newer versions of Mongodb (mongo-java-driver 3.0+), the API uses org.bson.Document, so your solution should look like this:

@RestController
public class ConfigurationController {

   @Autowired
   private MongoTemplate mongoTemplate;

   @RequestMapping(method = RequestMethod.PUT)
   ResponseEntity<?> add(@RequestBody String jsonString) {

       Document doc = Document.parse(jsonString)
       mongoTemplate.insert(doc, "foo");

       return new ResponseEntity<>(null, HttpStatus.CREATED);
   }

}
+12
source

Not the most pleasant solution, but something like this should work - change the controller to any line:

... add(@RequestBody String object) ...

and follow http://www.mkyong.com/mongodb/java-mongodb-convert-json-data-to-dbobject/

DBObject dbObject = (DBObject) com.mongodb.util.JSON.parse(object);
+3
source

json-simple lib, json- POJO, mongo

private JSONObject jsonSettings;
+1

, , , , "-" - . , ( JSON). , .

0

/ json, , , "Object" Pojo / DTO .
"Object" Spring Data MapStruct.
json json.

0

All Articles