SpringBoot中Web输出JSON对象中Date格式化成自定义的格式

2022-03-14 600点热度 0人点赞 0条评论

说明

在用SpringBoot做API输出的时候,我们希望输出的对象是转换成JSON格式的,另外如果对象中有日期类型,希望能够对日期进行统一的格式化。

实现

首先对SpringBoot项目进行配置(jsonMapper),新建MyConfiguration.java (如果有类似的配置文件,就只要修改就可以了)

@Configuration
public class MyConfiguration {

    @Bean(name = "jsonMapper")
    @Primary
    public ObjectMapper jsonMapper() {
        return new CustomObjectMapper();
    }

}

自定义ObjectMapper,新增CustomObjectMapper.java

其中就可以设置针对Date类型的,要转成json自定义序列化方法,这里还针对JSON的格式做了一些定制,如下:

public class CustomObjectMapper extends ObjectMapper {

    public CustomObjectMapper() {
        this.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        this.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
        SimpleModule module = new SimpleModule("JSONModule", new Version(2, 0, 0, null, null, null));
        module.addSerializer(Date.class, new CustDateSerializer());
        // module.addDeserializer(Date.class, new DateSerializer());
        // Add more here ...
        registerModule(module);
    }
}

新增CustDateSerializer.java

/**
 * @description 自定义返回JSON 数据格中日期格式化处理
 */
public class CustDateSerializer extends JsonSerializer<Date> {

    @Override
    public void serialize(Date value, JsonGenerator jsonGenerator,
            SerializerProvider provider) throws IOException {
        jsonGenerator.writeString(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(value));
    }

}

 

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论