Springboot统一配置localdatetime

参照文档:

其中画框的是 自定义时间的格式吗 yyyy-MM-dd HH:mm:ss

这个是设置序列化类。求求你看一眼源码,你应该就能明白。其实跟我之前给你的代码差不多的方式。

你可以试着把如下代码添加到项目中。它应该可以自动的处理你请求/响应对象中的LocalDateTime对象。

这代码我也只是连蒙带猜写的,我对Jackson不熟,我用Gson的。


import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

@Configuration
public class JacksHttpMessageConverterConfiguration {
	
	private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyy-MM-dd HH:mm:ss");
	
	private JsonSerializer<LocalDateTime> serializer = new JsonSerializer<LocalDateTime>() {
		@Override
		public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers)
				throws IOException {
			gen.writeString(value.format(formatter));
		}
	};
		
	private JsonDeserializer<LocalDateTime> deserializer = new JsonDeserializer<LocalDateTime>() {
		@Override
		public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt)
				throws IOException, JsonProcessingException {
			return LocalDateTime.parse(p.getText(), formatter);
		}
	};
	
	@Bean
	public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {

		Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder()
				.serializers(serializer)
				.deserializers(deserializer)
				.serializationInclusion(JsonInclude.Include.NON_NULL);
		return new MappingJackson2HttpMessageConverter(builder.build());
	}
}

1 Like