Spring Boot 配置Jackson

2021-03-06 02:29

阅读:423

标签:err   str   def   特性   boot   for   default   cep   ror   

Spring Boot 配置Jackson

编写配置类

@Configuration
public class JacksonConfig {

    @Bean
    public ObjectMapper objectMapper(){
        ObjectMapper objectMapper  = new ObjectMapper();
        //通过该方法对mapper对象进行设置,所有序列化的对象都将按改规则进行系列化
        // Include.Include.ALWAYS 默认
        // Include.NON_DEFAULT 属性为默认值不序列化
        // Include.NON_EMPTY 属性为 空("") 或者为 NULL 都不序列化,则返回的json是没有这个字段的。这样对移动端会更省流量
        // Include.NON_NULL 属性为NULL 不序列化
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        //反序列化的时候 忽略不匹配的属性
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,true);
        // 允许出现特殊字符和转义符
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
        // 允许出现单引号
        objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        //字段保留,将null值转为"" name==null  name转成""
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator,
                                  SerializerProvider serializerProvider)
                    throws IOException {
                jsonGenerator.writeString("");
            }
        });
        //日期格式
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"));
        objectMapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL);
        return objectMapper;
    }

}

或者配置文件

spring:
    jackson:
      # 设置属性命名策略,对应jackson下PropertyNamingStrategy中的常量值,SNAKE_CASE-返回的json驼峰式转下划线,json body下划线传到后端自动转驼峰式
      property-naming-strategy: SNAKE_CASE
      # 全局设置@JsonFormat的格式pattern
      date-format: yyyy-MM-dd HH:mm:ss
      # 当地时区
      locale: zh
      # 设置全局时区
      time-zone: GMT+8
      # 常用,全局设置pojo或被@JsonInclude注解的属性的序列化方式
      default-property-inclusion: NON_NULL #不为空的属性才会序列化,具体属性可看JsonInclude.Include
      # 常规默认,枚举类SerializationFeature中的枚举属性为key,值为boolean设置jackson序列化特性,具体key请看SerializationFeature源码
      serialization:
        WRITE_DATES_AS_TIMESTAMPS: true # 返回的java.util.date转换成timestamp
        FAIL_ON_EMPTY_BEANS: true # 对象为空时是否报错,默认true
      # 枚举类DeserializationFeature中的枚举属性为key,值为boolean设置jackson反序列化特性,具体key请看DeserializationFeature源码
      deserialization:
        # 常用,json中含pojo不存在属性时是否失败报错,默认true
        FAIL_ON_UNKNOWN_PROPERTIES: false
      # 枚举类MapperFeature中的枚举属性为key,值为boolean设置jackson ObjectMapper特性
      # ObjectMapper在jackson中负责json的读写、json与pojo的互转、json tree的互转,具体特性请看MapperFeature,常规默认即可
      mapper:
        # 使用getter取代setter探测属性,如类中含getName()但不包含name属性与setName(),传输的vo json格式模板中依旧含name属性
        USE_GETTERS_AS_SETTERS: true #默认false
      # 枚举类JsonParser.Feature枚举类中的枚举属性为key,值为boolean设置jackson JsonParser特性
      # JsonParser在jackson中负责json内容的读取,具体特性请看JsonParser.Feature,一般无需设置默认即可
      parser:
        ALLOW_SINGLE_QUOTES: true # 是否允许出现单引号,默认false
      # 枚举类JsonGenerator.Feature枚举类中的枚举属性为key,值为boolean设置jackson JsonGenerator特性,一般无需设置默认即可
      # JsonGenerator在jackson中负责编写json内容,具体特性请看JsonGenerator.Feature

Jackson工具类

@Component
@Slf4j
public class JacksonUtil {
    @Autowired
    private ObjectMapper objectMapper;
    //把任意对象转成json字符串
    public String writeAsString(Object obj){
        try {
            String s = objectMapper.writeValueAsString(obj);
            return s;
        }catch (JsonProcessingException e) {
            log.error("object convert json exception,obj:{}",obj);
            throw  new RuntimeException(e);
        }
    }
    //把json字符串转换为对象 对象得指定class
    public T readValue(String str,Class tClass){
        try {
            return objectMapper.readValue(str, tClass);
        } catch (JsonProcessingException e) {
            log.error("str convert Object exception,str:{},class:{}",str,tClass);
            throw  new RuntimeException(e);
        }
    }
    //json字符串转换为集合
    public  List readValueList(String str, Class tClass){
        try {
            TypeFactory typeFactory = TypeFactory.defaultInstance();
            return objectMapper.readValue(str,typeFactory.constructParametricType(List.class,tClass));
        } catch (JsonProcessingException e) {
            log.error("str convert List exception,str:{},class:{}",str,tClass);
            throw  new RuntimeException(e);
        }
    }
    //json对象转成map
    public  Map readValueMap(String str, Class tClass, Class vClass){
        try {
            TypeFactory typeFactory = TypeFactory.defaultInstance();
            return objectMapper.readValue(str,typeFactory.constructParametricType(HashMap.class,tClass,vClass));
        } catch (JsonProcessingException e) {
            log.error("str convert Map exception,str:{},tClass:{},vClass:{}",str,tClass,vClass);
            throw  new RuntimeException(e);
        }
    }
    public Map readValueMap(String str){
        try {

            return objectMapper.readValue(str,HashMap.class);
        } catch (JsonProcessingException e) {
            log.error("str convert Map exception,str:{}",str);
            throw  new RuntimeException(e);
        }
    }
}

Spring Boot 配置Jackson

标签:err   str   def   特性   boot   for   default   cep   ror   

原文地址:https://www.cnblogs.com/zero-vic/p/14313196.html


评论


亲,登录后才可以留言!