spring自带Jackson处理器忽略null

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/loverycjj/article/details/79898296

Spring Web使用Jackson来实现JSON的序列化

我们假设我们请求属性名字是小写的带下划线字母,而不是驼峰命名法的情况。为了减少响应的大小,我们也要求不要包括为空的属性。
默认情况下,响应被格式化成下面这样:

{    
    "status": "OK",    
    "data": {    
        "id": 1,    
        "name": "Room 1",    
        "roomCategoryId": 1,    
        "description": "Nice, spacious double bed room with usual amenities"    
    },    
    "error": null 
}

首先我们创建一个WebMvcConfigurerAdapter的继承,然后我们提供指示给Jackson怎样格式化JSON信息:

@Configuration
@EnableWebMvc
public class JsonConfiguration extends WebMvcConfigurerAdapter {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new MappingJackson2HttpMessageConverter(new Jackson2ObjectMapperBuilder().propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE).serializationInclusion(JsonInclude.Include.NON_NULL)
                .build()));
    }
}

我们配置这个转换器格式名字属性为小写带下划线格式,且我们告诉Jackson忽略null属性。结果将被格式化为如下JSON:

{
    "status": "OK",  
    "data": {    
        "id": 1,    
        "name": "Room 1",    
        "room_category_id": 1,    
        "description": "Nice, spacious double bed room with usual amenities"  
    } 
}

我们可以看到error属性现在消失了,且客房目录ID属性名被格式化成了我们讨论过的格式驼峰命名变下划线命名。

猜你喜欢

转载自blog.csdn.net/loverycjj/article/details/79898296
今日推荐