Reputation: 1223
I'd like to take HTTP PUT request with JSON and store it unmodified in Mongo. How can I do this? The best I have is this:
@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);
}
}
Upvotes: 16
Views: 31748
Reputation: 36
To store raw json object/array, all you have to do is to declare the type as "Object" in the Pojo and/or DTO level on your server side.
The "Object" type will work with Spring Data and MapStruct too.
Then on the client side, you can send your json data as a json data.
Upvotes: 0
Reputation: 1571
I am not sure if this helps, if you have option to create a Map in your Document then create it and later populate the "key-value" pairs in the hash map and store it. It will be stored as you expect (which is a JSON). This will be helpful when you do not know the name of the key or value during compile time.
Upvotes: 0
Reputation: 2129
You can use json-simple lib, it has small and elegant json object and use it in your model POJO and it will be converted to mongo Object type automatically
private JSONObject jsonSettings;
Upvotes: 1
Reputation: 5616
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);
}
}
Upvotes: 26
Reputation: 4683
Not maybe nicest solution, but something like this should work - change controller to accept any string:
... 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);
Upvotes: 3