Maison  >  Article  >  Java  >  Méthode de formatage de date Jackson dans SpringBoot

Méthode de formatage de date Jackson dans SpringBoot

王林
王林avant
2023-05-20 11:46:541199parcourir

Compétences de formatage de date de Jackson

Lors de l'utilisation de Spring Boot, vous devez utiliser Jackson pour gérer certains problèmes de sérialisation JSON de type Java Time API Lors du traitement des champs de certaines classes, vous pouvez spécifier le format en ajoutant directement des annotations au style des propriétés. Cependant, hier, un collègue a rencontré un problème de formatage Map des données, le problème de style de formatage ne peut donc pas être résolu en ajoutant des annotations.

Après diverses recherches sur Internet et diverses tentatives, j'ai finalement résolu ce problème et l'ai enregistré pour référence future.

Sans plus tarder, passons directement au code :

package com.diguage.demo.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.StdDateFormat;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import static com.fasterxml.jackson.databind.SerializationFeature.*;
import static java.time.format.DateTimeFormatter.ofPattern;
/<strong>
 * 配置类
 *
 * @author D瓜哥 · <a href="https://www.diguage.com/" rel="external nofollow"  rel="external nofollow"  target="_blank" >https://www.diguage.com</a>
 */
@Configuration
public class Config {
    /</strong>
     * 创建 ObjectMapper 对象,配置日期格式化
     *
     * @author D瓜哥 · <a href="https://www.diguage.com/" rel="external nofollow"  rel="external nofollow"  target="_blank" >https://www.diguage.com</a>
     */
    @Bean
    @Primary
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        String dateTimepattern = "yyyy-MM-dd HH:mm:ss";
        String datePattern = "yyyy-MM-dd";
        DateFormat dateFormat = new SimpleDateFormat(dateTimepattern);
        mapper.setDateFormat(dateFormat);
        mapper.configure(WRITE_DATES_AS_TIMESTAMPS, false);
        mapper.setDateFormat(new StdDateFormat().withColonInTimeZone(true));
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addDeserializer(LocalDate.class,
                new LocalDateDeserializer(ofPattern(datePattern)));
        javaTimeModule.addSerializer(LocalDate.class,
                new LocalDateSerializer(ofPattern(datePattern)));
        javaTimeModule.addDeserializer(LocalDateTime.class,
                new LocalDateTimeDeserializer(ofPattern(dateTimepattern)));
        javaTimeModule.addSerializer(LocalDateTime.class,
                new LocalDateTimeSerializer(ofPattern(dateTimepattern)));
        mapper.registerModule(javaTimeModule);
        return mapper;
    }
}

Questions complémentaires

Je me demande comment il se comportera lors du traitement de certains champs avec des annotations de style de formatage après avoir spécifié le style de formatage de la date de cette manière ? Ayez la chance de le tester.

Supplément : Format de conversion de date de configuration unifiée Jackson

Méthode 1 : Configurez

spring:
    jackson:
        default-property-inclusion: ALWAYS
        time-zone: GMT+8
        date-format: yyyy-MM-dd HH:mm:ss

dans le fichier de configuration yml. Après la sérialisation, le type de date sera formaté au format de la configuration.

Méthode 2 : Configurer dans la classe de configurationCréer JacksonConfig.java

@Configuration
public class JacksonConfig {

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public Jackson2ObjectMapperBuilderCustomizer customJackson() {
        return new Jackson2ObjectMapperBuilderCustomizer() {
            @Override
            public void customize(Jackson2ObjectMapperBuilder builder) {
                builder.serializerByType(LocalDateTime.class,
                        new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                builder.serializerByType(LocalDate.class,
                        new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                builder.serializerByType(LocalTime.class,
                        new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
                builder.deserializerByType(LocalDateTime.class,
                        new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                builder.deserializerByType(LocalDate.class,
                        new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                builder.deserializerByType(LocalTime.class,
                        new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
                builder.serializationInclusion(JsonInclude.Include.NON_NULL);
                builder.failOnUnknownProperties(false);
                builder.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
            }
        };
    }
}

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer