在Spring启动时使用Jackson反序列化Date对象

dddzy1tm  于 2022-11-09  发布在  Spring
关注(0)|答案(4)|浏览(137)

我的数据对象以1604571544010的形式返回数据,我需要一些可读性更强的数据。
我尝试了这么多东西,似乎没有什么工作,我怀疑有一个问题的Jackson或 Spring 版本。
我尝试在 application.properties 中设置数据格式
此外,我还尝试了baeldung中的所有全局配置

POM.xml文件

<jackson.version>2.11.3</jackson.version>
<jackson.databind.version>2.11.3</jackson.databind.version>
<jackson.mapper.version>1.9.13</jackson.mapper.version>
<spring.boot.version>2.1.17.RELEASE</spring.boot.version>
<spring.version>5.1.18.RELEASE</spring.version>

Web配置

@Bean
public Jackson2ObjectMapperBuilder jacksonBuilder()
{
    final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    return new Jackson2ObjectMapperBuilder().indentOutput(true).dateFormat(sdf);
}

数据传输对象

@JsonProperty
public Date getStartDateTime()
{
    return startDateTime;
}
13z8s7eq

13z8s7eq1#

您可以在www.example.com中添加属性spring.jackson.date-formatapplication.properties,以便为java.util.Date提供特定的日期格式。
例如spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
来源:Spring-Boot application.properties

r1wp621o

r1wp621o2#

唯一对我有效的全局设置是ObjectMapper

@Bean
        @Primary
        public ObjectMapper objectMapper()
        {
            final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            final ObjectMapper mapper = new ObjectMapper();
            mapper.setDateFormat(sdf);
            mapper.enable(SerializationFeature.INDENT_OUTPUT);
            return mapper;
        }
sr4lhrrt

sr4lhrrt3#

使用@JsonComponent。任何Date类型都将使用此自定义序列化程序进行序列化。

@JsonComponent
class DateSerializer extends JsonSerializer<Date> {

    public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());

    public DateSerializer() {
        this(null);
    }

    public DateSerializer(Class<Date> t) {
        super(t);
    }

    @Override
    public void serialize(
        Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {

        jgen.writeString(sdf.format(value));

    }
}

不使用@JsonComponent

WebConfiguration中注册自定义序列化程序。

@Configuration
@EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        SimpleModule m = new SimpleModule();
        m.addSerializer(Date.class, new DateSerializer());
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder().modules(m);
        converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
    }
}

或者如果要标记每个字段

@JsonSerialize(using = DateSerializer.class)
public Date getStartDateTime()
    {
        return startDateTime;
    }
htrmnn0y

htrmnn0y4#

全球解决方案:

@Slf4j
    @JsonComponent
    public class CustomDateDeserializer extends StdDeserializer<Date> {

        private static final long serialVersionUID = 1L;
        private final DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder()
                .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"))
                .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"))
                .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"))
                .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssZ"))
                .toFormatter();

        public CustomDateDeserializer() {
            this(null);
        }

        public CustomDateDeserializer(Class<?> vc) {
            super(vc);
        }

        @Override
        public Date deserialize(JsonParser jsonparser, DeserializationContext context)
                throws IOException, JsonProcessingException {
            String date = jsonparser.getText();
            //if(date == null || date.isBlank()) return null;
            if (NumberUtils.isParsable(date)) {
                try {
                    return new Date(Long.parseLong(date));
                } catch (Exception e) {
                    log.trace("Long Unparseable date: \"" + date + "\"");
                    throw new RuntimeException("LongUnparseable date: \"" + date + "\"");
                }
            }
            try {
            LocalDateTime dateToConvert = LocalDateTime.parse(jsonparser.getText(), dateFormatter);
            return java.sql.Timestamp.valueOf(dateToConvert);
            } catch (Exception e) {
                log.error("Error parsing date: \"" + date + "\" : ", e);
                throw new RuntimeException("Unparseable date: \"" + date + "\"");
            }

        }

    }

`
它与Chayne发布的解决方案相同,但使用DateTimeFormatter而不是SimpleDateFormat,因为DateTimeFormatter是线程安全的。

相关问题