【问题标题】:Return an object using ResponseEntity with JSONObject as one of the object's field使用带有 JSONObject 作为对象字段之一的 ResponseEntity 返回一个对象
【发布时间】:2018-03-15 09:21:33
【问题描述】:

我的模型如下所示,其中 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 在 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 的所有字段的模型类,我们不能实现这一点吗?

【问题讨论】:

  • 你是如何从控制器层发送这个对象的?
  • 作为列表

标签: json rest spring-restcontroller objectmapper


【解决方案1】:

想通了。

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

【讨论】:

    【解决方案2】:

    需要返回List&lt;Book&gt;类型的ResponseEntity

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

    【讨论】:

    • 如果我们使用 JSONObject 作为其中一种类型,这将不起作用。将其更改为 Map 并且它有效 - 检查下面的答案
    猜你喜欢
    • 2020-03-28
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 2019-09-05
    相关资源
    最近更新 更多