得到这个错误 No serializer found for class org.json.JSONObject and no properties found to create BeanSerializer

问题描述

@Entity
@Data
@JsonIgnoreProperties(ignoreUnkNown = true)
public class SomeRandomEntity {
  private String var1;
  private String var2;
  private String var3;
  public JSONObject getJSONObject throws JSONException {
        JSONObject properties = new JSONObject();
        properties.put("var1",getvar1());
        properties.put("var2",getvar2());
        properties.put("var3",getvar3());
        return properties;
    }
}

这个 POJO 对象以 json 对象的形式提供给前端。但是在前端获取数据时出现此错误

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing Failed; nested exception is org.springframework.http.converter.HttpMessageConversionException: 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) (through reference chain: org.springframework.data.domain.PageImpl["content"]->java.util.Collections$UnmodifiableRandomAccessList[0]->com.artifact.group.somRandomDTO["jsonobject"])] with root cause 
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) (through reference chain: org.springframework.data.domain.PageImpl["content"]->java.util.Collections$UnmodifiableRandomAccessList[0]->com.artifact.group.somRandomDTO["jsonobject"])

当我在 getJSONObject 中添加 @JsonIgnore 时,错误消失了。 getJSONObject 方法被认为是一种 getter 方法,jackson 也尝试对其进行序列化。我想了解 jackson 的这种行为以及为什么 @JsonIgnore 正在纠正错误

解决方法

这里,当您返回它作为响应时,您的对象使用 Serialized 获取 ObjectMapper 到 json 字符串,该字符串在 spring 的 MessageConverter(即 Jackson2HttpMessageConverter)bean 中使用。现在错误是由 ObjectMapper 如何序列化您的类引起的。您的班级有 4 个字段,3 个 String 类型和 1 个 JSONObject 类型。 ObjectMapper 在序列化字段时,尝试根据字段类型找到对应的序列化器。对于诸如 String 之类的已知类型,有一些开箱即用的序列化程序实现,但是对于您的自定义类型,您需要通过设置属性 ObjectMapper 的配置为 SerializationFeature.FAIL_ON_EMPTY_BEANS bean 提供序列化程序到false

ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false);

要验证这一点,您可以将方法 getJSONObject 的返回类型更改为 String(如下所示),您的代码将起作用。

public String getJSONObject throws JSONException {
        JSONObject properties = new JSONObject();
        properties.put("var1",getVar1());
        properties.put("var2",getVar2());
        properties.put("var3",getVar3());
        return properties.toString();
    }