@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为什么要纠正错误?
1条答案
按热度按时间omtl5h9j1#
在这里,当你把它作为回应返回时,你的对象是
Serialized
使用ObjectMapper
用于Spring的信息转换器(即Jackson2HttpMessageConverter
)豆子。现在这个错误是怎么造成的ObjectMapper
序列化类。你们班有4个文件,3个类型String
和类型1JSONObject
.ObjectMapper
序列化字段时,尝试根据字段类型查找相应的序列化程序。对于已知类型,有一些现成的序列化程序实现,如String
但是对于您的自定义类型,您需要提供序列化程序ObjectMapper
通过set属性配置beanSerializationFeature.FAIL_ON_EMPTY_BEANS
至false
.要验证这一点,可以更改方法的返回类型
getJSONObject
至String
(如下所示)代码将正常工作。