防止json结果中的空值(spring) [英] Prevent null values in json result (spring)

查看:174
本文介绍了防止json结果中的空值(spring)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我的JSON结果中有很多的空值(谈论大约1000多个),我想从该结果中排除。

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.

我搜索了很多,发现了很多关于此的问题/答案,但找不到适合我的情况:

I've searched a lot and found a lot of questions/answers about this, but couldn't find something for my situation:


  • 我正在使用Spring 4.0.1和更快的xml.jackson 2.4.2

  • 使用Spring Boot

  • 我不能简单地覆盖spring-mvc ObjectMapper,因为有很多端点会受其影响

  • 我的域模型是自动生成的外部XML文件,所以我无法向该域模型添加注释

  • I'm using Spring 4.0.1 and fasterxml.jackson 2.4.2
  • I'm not using Spring Boot
  • I cannot simply override the spring-mvc ObjectMapper, since there are a LOT of endpoints that would be affected by it
  • My domain-model is auto-generated from an external XML file, so I can't add annotations to that domain-model

所以基本上我想做以下其中一项:

So basically I would like to do one of the following:


  • 为自动生成的域类添加等效的注释(例如设置包结构或其他内容)

  • 覆盖Spring用于一个特定控制器的ObjectMapper,t o添加 objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

  • Add the equivalent of annotations for auto-generated domain classes (e.g. setting on package structure or something)
  • Override the ObjectMapper that Spring uses for one specific controller, to add objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

是有没有办法实现这个目标?

Is there any way to achieve this?

提前致谢!

推荐答案

我通过为控制器实现自己的objectMapper解决了我的问题。
webservices现在必须返回一个String而不是一个对象或一个List

I've solved my problem by implementing an own objectMapper for the controller. The webservices now must return a String instead of an object or a List

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;
}

这篇关于防止json结果中的空值(spring)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆