当前位置: 首页 > 知识库问答 >
问题:

获取此错误时,找不到类org的序列化程序。json。JSONObject,未发现创建BeanSerializer的属性

丁业
2023-03-14
@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方法,杰克逊也试图序列化它。我想了解杰克逊的这种行为,以及为什么@JsonIgnore正在纠正错误?

共有1个答案

汪鸿志
2023-03-14

在这里,当您返回它作为响应时,您的对象将使用spring的MessageConverter(即Jackson2HttpMessageConverter)bean中使用的对象映射器(ObjectMapper)将其序列化为json字符串。现在,这个错误是由于ObjectMapper如何序列化类引起的。您的类有4个字段,3个类型为字符串,1个类型为JSONObject<代码>ObjectMapper序列化字段时,尝试根据字段类型查找相应的序列化程序。对于已知类型(如String),有一些现成的序列化器实现,但对于自定义类型,您需要通过set属性的配置向ObjectMapperbean提供序列化器。FAIL\u ON\u EMPTY\u 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();
    }
 类似资料: