Ik heb een perfecte oplossing gevonden. neem bijvoorbeeld mijn project:
@Data
@Document(collection = "logs")
public class Log {
@Id
private String id;
private Object data;
// data field can be a string
public void setData(String str) {
data = str;
}
// data field can be a {}
public void setData(JsonObject jsonObject) {
data = new BasicDBObject(jsonObject.getMap());
}
// data can be a []
public void setData(JsonArray jsonArray) {
BasicDBList list = new BasicDBList();
list.addAll(jsonArray.getList());
data = list;
}
}
declareer de data
veld als type Object
, implementeer er 3 soorten setter voor.
Hier zijn de testcase:
@RunWith(SpringRunner.class)
@SpringBootTest
public class LogRepositoryTest {
@Autowired
private LogRepository logRepository;
@Test
public void test() {
Log strLog = new Log();
strLog.setData("string here");
logRepository.save(strLog);
Log objLog = new Log();
objLog.setData(new JsonObject().put("key", "value").put("obj", new JsonObject()));
logRepository.save(objLog);
Log aryLog = new Log();
aryLog.setData(new JsonArray().add("a").add("b").add("c"));
logRepository.save(aryLog);
}
}
En het resultaat:
{
"_id" : ObjectId("5a09fa46a15b065268a0a157"),
"_class" : "ltd.linkcon.spider.domain.Log",
"data" : "string here"
}
{
"_id" : ObjectId("5a09fa46a15b065268a0a158"),
"_class" : "ltd.linkcon.spider.domain.Log",
"data" : {
"key" : "value",
"obj" : [ ]
}
}
{
"_id" : ObjectId("5a09fa46a15b065268a0a159"),
"_class" : "ltd.linkcon.spider.domain.Log",
"data" : [
"a",
"b",
"c"
]
}