这是我将 Map 转换为 POJO 的代码:
public static <T> T createTObject(Class<T> clazz, Map<String,Object> toConvert){
final ObjectMapper mapper = new ObjectMapper();
T obj = null;
try {
obj = mapper.convertValue(toConvert, clazz);
} catch (JsonSyntaxException e) {
throw new MungoException("Cannot create object because JSON string is malformed");
} catch(Exception e) {
throw new MungoException("Some other error occurred when trying to deserialize JSON string. Check if POJO field names match with the Map keys.");
}
return obj;
}
问题是当我为此方法运行 JUnit 测试时,它会引发此错误:
java.lang.IllegalArgumentException: No suitable constructor found for type [simple type, class com.mungoae.MungoTest$Greeting]: can not instantiate from JSON object (need to add/enable type information?)
at [Source: N/A; line: -1, column: -1]
任何人都可以建议我解决此错误吗?
更新:
这是引发此错误的测试:
@Test
public void testMapDBObjectToPOJO(){
Map<String,Object> map = new HashMap<String,Object>();
map.put("greeting", "Hello world!");
map.put("_id", "51cc93ad23187afa8e0a4433");
Greeting greeting = Mapper.createTObject(Greeting.class, map);
assertNotNull(greeting);
assertEquals("Hello world!", greeting.getGreeting());
}