//测试实例
String json = "{\"_id\": \"1234567\", \"name\": \"人类资料库\", \"personList\": [{\"wight\": 160, \"name\": \"一个男人\", \"age\": 18, \"birthday\": {\"$date\": \"2023-02-01T03:16:44.861Z\"}, \"_class\": \"com.allinmd.cn.case_history.admin.test.utils.MongoTest$Man\"}, {\"height\": 170, \"name\": \"一个女人\", \"age\": 16, \"birthday\": {\"$date\": \"2023-01-31T03:16:44.861Z\"}, \"_class\": \"com.allinmd.cn.case_history.admin.test.utils.MongoTest$Women\"}], \"_class\": \"com.allinmd.cn.case_history.admin.test.utils.MongoTest$HumanInfo\"}";
@Test
public void test11(){
Document parse = Document.parse(json);
MongoConverter converter = mongoTemplate.getConverter();
TypeInformation<?> typeInformation = converter.getTypeMapper().readType(parse);
if (typeInformation != null) {
Class<?> type = typeInformation.getType();
Object read = converter.read(type, parse);
System.out.println(read);
}
}
背景:
1、如果在工具中直接执行insert语句,会导致字段类型丢失,以及一些时间日期格式的不能正确导入;
2、如果不经过JSON->BSON->Object,直接JSON->Object,则会导致数据内的类型(_class)丢失;
实体的结构:
@Data
static class Person{
private String name;
private Integer age;
private Date birthday;
}
@Data
@EqualsAndHashCode(callSuper = false)
static class Man extends Person{
private Integer wight;
}
@Data
@EqualsAndHashCode(callSuper = false)
static class Women extends Person{
private Integer height;
}
@Data
static class HumanInfo{
@MongoId
private String id;
/**
*
*/
private String name;
private List<Person> personList;
}