我有一个返回 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 的对象映射器中定义
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 中的空值有什么建议吗?
最佳答案
Include.NON_NULL
不起作用,因为 JSONNull
表示 null
但它不是 null
per se。来自 documentation :
JSONNull is equivalent to the value that JavaScript calls null, whilst Java's null is equivalent to the value that JavaScript calls undefined.
这个对象是作为一个 Singleton
实现的,它有两个方法:isArray
和 isEmpty
其中 isEmpty
是有问题的因为抛出异常。下面的代码片段显示了它的实现:
public boolean isEmpty() {
throw new JSONException("Object is null");
}
最好的方法是为JSONNull
类型定义NullSerializer
。下面的示例显示了我们如何配置它:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.NullSerializer;
import net.sf.json.JSONArray;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;
public class JsonApp {
public static void main(String[] args) throws Exception {
SimpleModule netSfJsonModule = new SimpleModule("net.sf.json");
netSfJsonModule.addSerializer(JSONNull.class, NullSerializer.instance);
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.registerModule(netSfJsonModule);
JSONObject object = new JSONObject();
object.accumulate("object", JSONNull.getInstance());
JSONArray jsonArray = new JSONArray();
jsonArray.add(object);
JSONObject json = new JSONObject();
json.accumulate("list", jsonArray);
System.out.println(mapper.writeValueAsString(json));
}
}
以上代码打印:
{
"list" : [ {
"object" : null
} ]
}
另见:
关于json - Spring 启动 JsonMappingException : Object is null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54744703/