GVKun编程网logo

SpringBoot json null 转成空字符(java json null转空字符串)

18

在本文中,我们将为您详细介绍SpringBootjsonnull转成空字符的相关知识,并且为您解答关于javajsonnull转空字符串的疑问,此外,我们还会提供一些关于IntelliJIDEA201

在本文中,我们将为您详细介绍SpringBoot json null 转成空字符的相关知识,并且为您解答关于java json null转空字符串的疑问,此外,我们还会提供一些关于IntelliJ IDEA 2017 版 SpringBoot 的 Json 字符串返回、Spring Boot 10:处理Json数据中的null值、spring boot @ResponseBody 转换 JSON 时 Date 类型处理方法,Jackson 和 FastJson 两种方式,springboot 2.0.9 配置 fastjson 不生效官...、spring boot 下对JSON返回值去除null和空字段操作的有用信息。

本文目录一览:

SpringBoot json null 转成空字符(java json null转空字符串)

SpringBoot json null 转成空字符(java json null转空字符串)

SpringBoot json null过滤为空字符串

@Configuration
public class JacksonConfig {

    @Bean
    public Jackson2ObjectMapperBuilder objectMapperBuilder() {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.featuresToDisable(
                SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,
                DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
        return builder;
    }

    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
                jsonGenerator.writeString("");
            }
        });
        return objectMapper;
    }

}

IntelliJ IDEA 2017 版 SpringBoot 的 Json 字符串返回

IntelliJ IDEA 2017 版 SpringBoot 的 Json 字符串返回

一、说明

      SpringBoot 框架已经自动封装好 json 字符串解析,所以我们只需要用它的注解来返回操作就可以了.

二、实战

     1、书写一个实体类 User,设置属性 id 和 name     

 1 package com.json;
 2 
 3 /**
 4  * Created by liuya on 2018-01-17.
 5  */
 6 public class UserPoJo
 7 {
 8     private int userId;
 9     private String userName;
10 
11     public int getUserId() {
12         return userId;
13     }
14 
15     public void setUserId(int userId) {
16         this.userId = userId;
17     }
18 
19     public String getUserName() {
20         return userName;
21     }
22 
23     public void setUserName(String userName) {
24         this.userName = userName;
25     }
26 
27     @Override
28     public String toString() {
29         return "UserPoJo{" +
30                 "userId=" + userId +
31                 ", userName=''" + userName + ''\'''' +
32                 ''}'';
33     }
34 }
View Code

    2、书写开启服务器的代码(SpringBoot 框架自带一个测试服务器)

 1 package com.json;
 2 
 3 import org.springframework.boot.SpringApplication;
 4 import org.springframework.boot.autoconfigure.SpringBootApplication;
 5 
 6 
 7 @SpringBootApplication
 8 public class SpringboothelloApplication {
 9 
10 
11     public static void main(String[] args) {
12         SpringApplication.run(SpringboothelloApplication.class, args);
13     }
14 
15 
16 
17 }
View Code

   3、书写 controller 返回 json 的代码

 1 package com.json;
 2 
 3 import org.springframework.web.bind.annotation.RequestMapping;
 4 import org.springframework.web.bind.annotation.RestController;
 5 
 6 /**
 7  * Created by liuya on 2018-01-16.
 8  *
 9  *  测试用的一个例子
10  */
11 
12 
13 @RestController
14 public class ControllerJson {
15 
16     @RequestMapping("user")
17     public UserPoJo hello(){
18         //实体类赋值
19         UserPoJo userPoJo  = new UserPoJo();
20         userPoJo.setUserId(111);
21         userPoJo.setUserName("王小二");
22         //返回实体类
23         return userPoJo;
24     }
25 }
View Code

   4、启动服务器的代码,生成如图

     

5、浏览器测试

     

Spring Boot 10:处理Json数据中的null值

Spring Boot 10:处理Json数据中的null值

Jackson版:

/**
 * Jackson 配置类 对Json数据进行特殊处理
 *
 * @Author YangXuyue
 * @Date 2019/04/02 07:12
 */
@Configuration
public class JacksonConfig {

    /**
     * 配置Jackson
     *
     * @param builder
     * @return
     * @Author YangXuyue
     * @Date 2019/04/02 07:14
     */
    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object o,
                                  JsonGenerator jsonGenerator,
                                  SerializerProvider serializerProvider) throws IOException {
                jsonGenerator.writeString("");
            }
        });
        return objectMapper;
    }
}

 

spring boot @ResponseBody 转换 JSON 时 Date 类型处理方法,Jackson 和 FastJson 两种方式,springboot 2.0.9 配置 fastjson 不生效官...

spring boot @ResponseBody 转换 JSON 时 Date 类型处理方法,Jackson 和 FastJson 两种方式,springboot 2.0.9 配置 fastjson 不生效官...

spring boot @ResponseBody 转换 JSON 时 Date 类型处理方法 ,这里一共有两种不同解析方式(Jackson 和 FastJson 两种方式,springboot 我用的 1.x 的版本)

第一种方式:默认的 json 处理是 jackson 也就是对 configureMessageConverters 没做配置时

  mybatis 数据查询返回的时间,是一串数字,如何转化成时间。两种方法,推荐第一种

  方法一:

  可以在 apllication.property 加入下面配置就可以

  # 时间戳统一转换
  spring.jackson.date-format=yyyy-MM-dd HH:mm:ss

  spring.jackson.time-zone=GMT+8

 

  方法二:

  @JsonFormat(timezone = "GMT+8", pattern = "yyyyMMddHHmmss")

  private Date createTime;

 

第二种方式:当 configureMessageConverters 配置为 FasJson 处理时;

  方法一:全局配置:    fastJsonConfig.setDateFormat ("yyyy-MM-dd HH:mm:ss");

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

@Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);

        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();

        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty
        );

       //此处是全局处理方式
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");

        fastConverter.setFastJsonConfig(fastJsonConfig);

        List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
        supportedMediaTypes.add(MediaType.ALL); // 全部格式
        fastConverter.setSupportedMediaTypes(supportedMediaTypes);
        converters.add(fastConverter);
    }    
}

  

  方法二:在所需要的字段上配置(比较灵活的方式,根据不同需求转换):

  @JSONField(format="yyyyMMdd")

  private Date createTime;

说明:这里如果字段和全局都配置了 ,最后是以全局转换

 

重要补充:

当 springboot 版本是 2.0.9 以上配置 fastjson 不生效解决如下:

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class MyConfiguration {

    @Bean
    public HttpMessageConverters customConverters() {
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        // 创建配置类
        FastJsonConfig config = new FastJsonConfig();
        config.setSerializerFeatures(
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty
        );

        //此处是全局处理方式
        config.setDateFormat("yyyy-MM-dd HH:mm:ss");
        config.setCharset(Charset.forName("UTF-8"));
        fastConverter.setFastJsonConfig(config);

        List<MediaType> supportedMediaTypes = new ArrayList<>();
        supportedMediaTypes.add(MediaType.ALL);
        fastConverter.setSupportedMediaTypes(supportedMediaTypes);
        //支持text 转string
        StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
        return new HttpMessageConverters(fastConverter, stringHttpMessageConverter);
    }

 

 参考 spring 官网文档:https://docs.spring.io/spring-boot/docs/2.0.9.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-spring-mvc-message-converters

spring boot 下对JSON返回值去除null和空字段操作

spring boot 下对JSON返回值去除null和空字段操作

这篇文章主要介绍了spring boot 下对JSON返回值去除null和空字段操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

在开发过程中,我们需要统一返回前端json格式的数据,但有些接口的返回值存在 null或者""这种没有意义的字段。

不仅影响理解,还浪费带宽,这时我们可以统一做一下处理,不返回空字段,或者把NULL转成“”,spring 内置的json处理框架是Jackson。我们可以对它配置一下达到目的

直接看代码,很简单.

/** * 〈返回json空值去掉null和""〉 〈功能详细描述〉 * * @author gogym * @version 2017年10月13日 * @see JacksonConfig * @since */ @Configuration public class JacksonConfig { @Bean @Primary @ConditionalOnMissingBean(ObjectMapper.class) public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) { ObjectMapper objectMapper = builder.createXmlMapper(false).build(); // 通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化 // Include.Include.ALWAYS 默认 // Include.NON_DEFAULT 属性为默认值不序列化 // Include.NON_EMPTY 属性为 空("") 或者为 NULL 都不序列化,则返回的json是没有这个字段的。这样对移动端会更省流量 // Include.NON_NULL 属性为NULL 不序列化,就是为null的字段不参加序列化 //objectMapper.setSerializationInclusion(Include.NON_EMPTY); // 字段保留,将null值转为"" objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer() { @Override public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException { jsonGenerator.writeString(""); } }); return objectMapper; } }

补充知识:springboot RestController 配置fastjson,实体为null时不显示问题

Springboot 在和fastjson配合使用时,当返回实体为空时拦截不显示问题。在实际业务中,不管返回实体是否为空,都需要显示出来,如果为空则显示null。

解决方案,引入fastjson jar包

com.alibabafastjson1.2.22

添加配置ResultConfig:

package com.message.config; /** * @author :zoboy * @Description: * @ Date: Created in 2019-11-18 10:29 */ import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import java.util.ArrayList; import java.util.List; @Configuration public class ResultConfig { /*注入Bean : HttpMessageConverters,以支持fastjson*/ @Bean public HttpMessageConverters fastJsonHttpMessageConverters() { FastJsonHttpMessageConverter fastConvert = new FastJsonHttpMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteMapNullValue, SerializerFeature.disableCheckSpecialChar); fastJsonConfig.setDateFormat("yyyy-MM-dd hh:mm:ss"); //处理中文乱码问题 List fastMediaTypes = new ArrayList(); fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8); fastConvert.setSupportedMediaTypes(fastMediaTypes); fastConvert.setFastJsonConfig(fastJsonConfig); return new HttpMessageConverters((HttpMessageConverter>) fastConvert); } }

结果:

{ "code": "0", "message": "成功!", "data": null }

解决问题!

以上这篇spring boot 下对JSON返回值去除null和空字段操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持小编。

关于SpringBoot json null 转成空字符java json null转空字符串的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于IntelliJ IDEA 2017 版 SpringBoot 的 Json 字符串返回、Spring Boot 10:处理Json数据中的null值、spring boot @ResponseBody 转换 JSON 时 Date 类型处理方法,Jackson 和 FastJson 两种方式,springboot 2.0.9 配置 fastjson 不生效官...、spring boot 下对JSON返回值去除null和空字段操作等相关知识的信息别忘了在本站进行查找喔。

本文标签: