简体   繁体   English

防止json结果中出现null值(春季)

[英]Prevent null values in json result (spring)

Right now, I have a lot of null values in my JSON result (talking about some 1000+), which I want to exclude from that result. 现在,我的JSON结果中有很多空值(大约有1000多个),我想从结果中排除。

I've searched a lot and found a lot of questions/answers about this, but couldn't find something for my situation: 我进行了很多搜索,发现了很多与此相关的问题/答案,但找不到适合我的情况的东西:

  • I'm using Spring 4.0.1 and fasterxml.jackson 2.4.2 我正在使用Spring 4.0.1和fasterxml.jackson 2.4.2
  • I'm not using Spring Boot 没有使用Spring Boot
  • I cannot simply override the spring-mvc ObjectMapper, since there are a LOT of endpoints that would be affected by it 我不能简单地覆盖spring-mvc ObjectMapper,因为有很多端点会受到它的影响
  • My domain-model is auto-generated from an external XML file, so I can't add annotations to that domain-model 我的域模型是从外部XML文件自动生成的,因此我无法向该域模型添加注释

So basically I would like to do one of the following: 因此,基本上,我想执行以下操作之一:

  • Add the equivalent of annotations for auto-generated domain classes (eg setting on package structure or something) 为自动生成的域类添加等效的注释(例如,在程序包结构上进行设置等)
  • Override the ObjectMapper that Spring uses for one specific controller, to add objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); 重写Spring用于一个特定控制器的ObjectMapper,以添加objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

Is there any way to achieve this? 有什么办法可以做到这一点?

Thanks in advance! 提前致谢!

I've solved my problem by implementing an own objectMapper for the controller. 我通过为控制器实现自己的objectMapper解决了我的问题。 The webservices now must return a String instead of an object or a List 现在,Web服务必须返回字符串,而不是对象或列表

private ObjectMapper objectMapper;

@PostConstruct
private void configureObjectMapper() {
    objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
}

@RequestMapping(...)
@ResponseBody
public String getSomething(...) {
    try {
        return objectMapper.writeValueAsString(getSomething());
    } catch (JsonProcessingException e) {
        LOG.error("Could not serialize to JSON", e);
    }
    return null;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM