如何使用Spring Boot在Mongo中存储原始JSON
我希望使用JSON接收HTTP PUT请求,并将其未经修改地存储在Mongo中。我该怎么做?我最好的办法是:如何使用Spring Boot在Mongo中存储原始JSON,json,mongodb,spring-boot,Json,Mongodb,Spring Boot,我希望使用JSON接收HTTP PUT请求,并将其未经修改地存储在Mongo中。我该怎么做?我最好的办法是: @RestController public class ConfigurationController { @Autowired private MongoTemplate mongoTemplate; @RequestMapping public DBObject index() { return mongoTemplate.get
@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);
}
}
@RestController
公共类配置控制器{
@自动连线
私有MongoTemplate MongoTemplate;
@请求映射
公共数据库对象索引(){
返回mongoTemplate.getCollection(“foo”).findOne();
}
@RequestMapping(method=RequestMethod.PUT)
ResponseEntity添加(@RequestBody DBObject){
插入(对象,“foo”);
返回新的ResponseEntity(null,HttpStatus.CREATED);
}
}
也许不是最好的解决方案,但类似的方法应该可以工作-更改控制器以接受任何字符串:
... add(@RequestBody String object) ...
并遵循
在较新版本的Mongodb(mongo java driver 3.0+)中,API使用org.bson.Document,因此您的解决方案应如下所示:
@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);
}
}
@RestController
公共类配置控制器{
@自动连线
私有MongoTemplate MongoTemplate;
@RequestMapping(method=RequestMethod.PUT)
ResponseEntity添加(@RequestBody字符串jsonString){
Document doc=Document.parse(jsonString)
mongoTemplate.插入(文件“foo”);
返回新的ResponseEntity(null,HttpStatus.CREATED);
}
}
您可以使用json简单库,它有小巧优雅的json对象,并在您的模型POJO中使用,它将自动转换为mongo对象类型
private JSONObject jsonSettings;
我不确定这是否有帮助,如果您可以选择在文档中创建映射,然后创建它,然后在散列映射中填充“key-value”对并存储它。它将按照您期望的方式存储(这是一个JSON)。当您在编译时不知道键或值的名称时,这将非常有用。要存储原始json对象/数组,您只需在服务器端的Pojo和/或DTO级别将类型声明为“object”。
“Object”类型也适用于Spring数据和MapStruct。
然后在客户端,您可以将json数据作为json数据发送。如果我在json中设置id,它会更新文档吗?
private JSONObject jsonSettings;