获取此错误未找到类org.json.jsonobject的序列化程序,也未找到创建beanserializer的属性

mo49yndu  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(347)
@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对象的形式提供给frontend。但是在前端获取数据时,出现了这个错误。

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为什么要纠正错误?

omtl5h9j

omtl5h9j1#

在这里,当你把它作为回应返回时,你的对象是 Serialized 使用 ObjectMapper 用于Spring的信息转换器(即 Jackson2HttpMessageConverter )豆子。现在这个错误是怎么造成的 ObjectMapper 序列化类。你们班有4个文件,3个类型 String 和类型1 JSONObject . ObjectMapper 序列化字段时,尝试根据字段类型查找相应的序列化程序。对于已知类型,有一些现成的序列化程序实现,如 String 但是对于您的自定义类型,您需要提供序列化程序 ObjectMapper 通过set属性配置bean SerializationFeature.FAIL_ON_EMPTY_BEANSfalse .

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

要验证这一点,可以更改方法的返回类型 getJSONObjectString (如下所示)代码将正常工作。

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

相关问题