我的模型如下所示,其中bookJson是一个json对象 -
{
"name" : "somebook",
"author" : "someauthor"
}
public class Book{
private int id;
private JSONObject bookJson;
public int getId(){return this.id;}
public JSONObject getBookJson(){this.bookJson;}
public void setId(int id){this.id = id;}
public void setBookJson(JSONObject json){this.bookJson = json;}
}
JSONObject属于org.json包
当My RestController在ResponseEntity对象中返回Book对象时,我收到错误 -
"errorDesc": "Type definition error: [simple type, class org.json.JSONObject]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.json.JSONObject and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)
实现这一目标的最佳方法是什么?
如果没有一个包含bookJson所有字段的模型类,我们难道不能实现这个目标吗?
答案 0 :(得分:0)
想出来了。
将JSONObject添加为Map,并使用ObjectMapper进行所有转换。
public class Book{
private int id;
private Map<String, Object>bookJson;
public int getId(){return this.id;}
public Map<String, Object>getBookJson(){this.bookJson;}
public void setId(int id){this.id = id;}
public void setBookJson(Map<String, Object> json){this.bookJson = json;}
}
ObjectMapper mapper = new ObjectMapper();
try {
map = mapper.readValue(json, new TypeReference<Map<String, Object>>(){});
} catch (IOException e) {
throw new JsonParsingException(e.getMessage(), e);
}
答案 1 :(得分:0)
您需要返回List<Book>
类型的ResponseEntity。
public ResponseEntity<List<Book>> doSomething() {
return new ResponseEntity(bookList);
}