20°

SpringBoot 使用 Jackson 返回 JSON 数据日期格式化

@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 不序列化
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    // 允许出现特殊字符和转义符
    objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
    // 允许出现单引号
    objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
    // 字段保留,将null值转为""
    objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>()
    {
        @Override
        public void serialize(Object o, JsonGenerator jsonGenerator,
                              SerializerProvider serializerProvider)
                throws IOException
        {
            jsonGenerator.writeString("");
        }
    });
    return objectMapper;
}

//https://www.cnblogs.com/liaojie970/p/9396334.html

 

spring:
  jackson:
    #日期格式化
    date-format: yyyy-MM-dd HH:mm:ss
    serialization:
       #格式化输出 
      indent_output: true
      #忽略无法转换的对象
      fail_on_empty_beans: false
    #设置空如何序列化
    defaultPropertyInclusion: NON_EMPTY
    deserialization:
      #允许对象忽略json中不存在的属性
      fail_on_unknown_properties: false
    parser:
      #允许出现特殊字符和转义符
      allow_unquoted_control_chars: true
      #允许出现单引号
      allow_single_quotes: true
/**
     * 测试日期
     * @param joinDay
     * @return
     */
    @RequestMapping("date")
    public Date testDate(Date joinDay){
        return joinDay;
    }

package com.streamyear.course.config;

import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component;

import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List;

/**

  • 全局页面传入日期字符串,自动转换成日期格式 */ @Component public class DateConverterConfig implements Converter<String, Date> {

    private static final List<String> formarts = new ArrayList<>(4); static{ formarts.add("yyyy-MM"); formarts.add("yyyy-MM-dd"); formarts.add("yyyy-MM-dd hh:mm"); formarts.add("yyyy-MM-dd hh:mm:ss"); }

    @Override public Date convert(String source) { String value = source.trim(); if ("".equals(value)) { return null; } if(source.matches("^\d{4}-\d{1,2}$")){ return parseDate(source, formarts.get(0)); }else if(source.matches("^\d{4}-\d{1,2}-\d{1,2}$")){ return parseDate(source, formarts.get(1)); }else if(source.matches("^\d{4}-\d{1,2}-\d{1,2} {1}\d{1,2}:\d{1,2}$")){ return parseDate(source, formarts.get(2)); }else if(source.matches("^\d{4}-\d{1,2}-\d{1,2} {1}\d{1,2}:\d{1,2}:\d{1,2}$")){ return parseDate(source, formarts.get(3)); }else { throw new IllegalArgumentException("Invalid boolean value '" + source + "'"); } }

    /**

    • 格式化日期

    • @param dateStr String 字符型日期

    • @param format String 格式

    • @return Date 日期 */ public Date parseDate(String dateStr, String format) { Date date=null; try { DateFormat dateFormat = new SimpleDateFormat(format); date = dateFormat.parse(dateStr); } catch (Exception e) {

      } return date; }

}

@Configuration
public class JacksonConfiguration {

  @Bean
  public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    ObjectMapper objectMapper = new ObjectMapper();

    // 忽略json字符串中不识别的属性
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    // 忽略无法转换的对象 “No serializer found for class com.xxx.xxx”
    objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

    // NULL不参与序列化
//    objectMapper.setSerializationInclusion(Include.NON_NULL);
    // PrettyPrinter 格式化输出
    objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);

    // 指定时区,默认 UTC,而不是 jvm 默认时区
    objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
    // 日期类型处理
    objectMapper.setDateFormat(new SimpleDateFormat(DateUtil.DEFAULT_FORMAT_DATETIME));

    converter.setObjectMapper(objectMapper);
    return converter;
  }

  /**
   * BeanPostProcessor 的便捷实现,以便对带注解的方法上执行方法级别的校验
   * 注意:需要在目标类上室友 @Validated 注解进行注释,以便搜索其内联约束注释的方法
   * A convenient BeanPostProcessor implementation
   * that delegates to a JSR-303 provider for performing method-level validation on annotated methods
   * @return
   */
  @Bean
  public MethodValidationPostProcessor methodValidationPostProcessor() {
    return new MethodValidationPostProcessor();
  }

}

 

本文由【Online_Reus】发布于开源中国,原文链接:https://my.oschina.net/u/3020519/blog/3073669

全部评论: 0

    我有话说: