Return 使用 ResponseEntity 的对象,JSONObject 作为对象的字段之一

Return an object using ResponseEntity with JSONObject as one of the object's field

我的模型如下所示,其中 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 包

当我的 RestController returns Book 对象在 ResponseEntity 对象中时,我收到错误 -

 "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 所有字段的模型 class,我们不能实现这个吗?

想通了。

改为将 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);
    }

您需要 return List<Book> 类型的 ResponseEntity

public ResponseEntity<List<Book>> doSomething() {
  return new ResponseEntity(bookList);
}