I am new to Spring data and mongodb. I have a JSON object which represents a JSON Schema and I need to store that in mongodb using spring data. But the issue with JSON schem
Please find here the necessary code.
@lombok.Data
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Bounty {
String type;
Map items;
Map properties;
List
Here is my repository class
public interface BountyRepository extends MongoRepository {
}
And here is a controller snippet which u can use to try it out
@GetMapping("/insert/{number}")
public void insert(@PathVariable int number){
bountyRepository.save(getBounty(number));
}
public Bounty getBounty(int number){
ObjectMapper objectMapper = new ObjectMapper();
String jsonString1 = "{\n" +
" \"type\": \"object\",\n" +
" \"properties\": {\n" +
" \"name\": {\n" +
" \"type\": \"string\",\n" +
" \"minLength\": 10\n" +
" },\n" +
" \"age\": {\n" +
" \"type\": \"integer\"\n" +
" }\n" +
" },\n" +
" \"required\": [\n" +
" \"name\",\n" +
" \"age\"\n" +
" ]\n" +
"}";
String jsonString2 = "{\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"type\": \"object\",\n" +
" \"properties\": {\n" +
" \"abc\": {\n" +
" \"type\": \"boolean\"\n" +
" },\n" +
" \"xyz\": {\n" +
" \"$ref\": \"#/definitions/\"\n" +
" },\n" +
" \"asd\": {\n" +
" \"type\": \"null\"\n" +
" }\n" +
" },\n" +
" \"required\": [\n" +
" \"abc\",\n" +
" \"xyz\"\n" +
" ]\n" +
" }\n" +
"}";
try {
Bounty bounty1 = objectMapper.readValue(jsonString1, Bounty.class);
Bounty bounty2 = objectMapper.readValue(jsonString2, Bounty.class);
if (number == 1) return bounty1;
if (number == 2) return bounty2;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
This is how it looks like in Mongo after save.
/* 1 */
{
"_id" : ObjectId("58da2390fde4f133178499fa"),
"_class" : "pani.kiran.sumne.model.Bounty",
"type" : "object",
"properties" : {
"name" : {
"type" : "string",
"minLength" : 10
},
"age" : {
"type" : "integer"
}
},
"required" : [
"name",
"age"
]
}
/* 2 */
{
"_id" : ObjectId("58da23adfde4f133178499fb"),
"_class" : "pani.kiran.sumne.model.Bounty",
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"abc" : {
"type" : "boolean"
},
"xyz" : {
"$ref" : "#/definitions/"
},
"asd" : {
"type" : "null"
}
},
"required" : [
"abc",
"xyz"
]
}
}