【发布时间】:2019-07-11 16:26:33
【问题描述】:
我有一个返回 net.sf.json.JSONObject 的@RestController:
@PostMapping("/list")
public JSONObject listStuff(HttpServletRequest inRequest, HttpServletResponse inResponse) {
JSONObject json = new JSONObject();
...
return json;
}
当 JSONObject 包含空引用时,会抛出以下异常:
Could not write JSON: Object is null; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Object is null (through reference chain: net.sf.json.JSONObject[\"list\"]->net.sf.json.JSONArray[0]->net.sf.json.JSONObject[\"object\"]->net.sf.json.JSONNull[\"empty\"])"
这是我们现在正在清理的遗留代码,在某些时候我们将摆脱显式 JSON 操作,但这将是一个巨大的变化,现在我只想摆脱异常。 我尝试了以下解决方案:
- 在 Spring 的 Object Mapper 中定义
Include.NON_NULL- 所以这段代码在我的WebMvcConfigurationSupportClass中:
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters)
{
ObjectMapper webObjectMapper = objectMapper.copy();
webObjectMapper.setSerializationInclusion(Include.NON_NULL);
converters.add(new MappingJackson2HttpMessageConverter(webObjectMapper));
}
- 在 application.yml 中设置以下属性:
spring.jackson.default-property-inclusion=non_null - 检查
com.fasterxml.jackson的版本 - 在依赖关系树中找到的唯一版本是 2.9.7。
以上都没有帮助。
关于如何告诉 Spring 忽略 net.sf.json.JSONObjects 中的空值有什么建议吗?
【问题讨论】:
-
你也试过
spring.jackson.default-property-inclusion=NON_ABSENT吗?请注意,这是NON_ABSENT而不是NON_NULL -
用 NON_ABSENT 和 NON_EMPTY 尝试了你的建议 - 仍然没有工作。
-
net.sf.json.JSONObject类来自的库的名称和版本是什么? -
<groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId><version>2.4</version>
标签: json spring spring-boot jackson