在Spring Rest API中配置LocaldateTime

unftdfkk  于 2023-02-18  发布在  Spring
关注(0)|答案(5)|浏览(132)

我使用Java 10和最新的Spring启动器2.1.0版本
POM配置:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
    </parent>

    <dependencies>          
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
            <version>2.9.7</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.7</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-jaxb-annotations</artifactId>
            <version>2.9.7</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.jaxrs</groupId>
            <artifactId>jackson-jaxrs-json-provider</artifactId>
            <version>2.9.7</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.woodstox</groupId>
            <artifactId>woodstox-core-asl</artifactId>
            <version>4.4.1</version>
        </dependency>
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.1</version>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-core</artifactId>
            <version>2.3.0.1</version>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-impl</artifactId>
            <version>2.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct-jdk8</artifactId>
            <version>1.2.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.jxls</groupId>
            <artifactId>jxls-poi</artifactId>
            <version>1.0.15</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>8.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security.oauth</groupId>
            <artifactId>spring-security-oauth2</artifactId>
            <version>2.3.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security.oauth.boot</groupId>
            <artifactId>spring-security-oauth2-autoconfigure</artifactId>
            <version>2.1.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.session</groupId>
            <artifactId>spring-session-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
    </dependencies>

静止终点:

@GetMapping("{id}")
    public ResponseEntity<?> get(@PathVariable String id) {
        return transactionRepository
                .findById(Integer.parseInt(id))
                .map(mapper::toDTO)
                .map(ResponseEntity::ok)
                .orElseGet(() -> notFound().build());
    }

日期:

public class PaymentTransactionsDTO {

    private Integer id;

    private String status;

    private LocalDateTime created_at;

    private String merchant;
    .... getters and setters
}

但是当我尝试返回LocalDateTime created_at的JSON数据时,我得到了空结果。我猜想LocalDateTime没有正确转换为JSON值。
你能建议我如何解决这个问题吗?

m0rkklqb

m0rkklqb1#

JSON序列化是由Jackson的ObjectMapper驱动的,我建议显式配置它。

  • 注册JavaTimeModule
  • 禁止将日期写为时间戳
  • 设置日期格式(使用StdDateFormat

StdDateFormat的描述:
标准日期序列化程序和反序列化程序使用的默认DateFormat实现。对于序列化,默认使用ISO-8601兼容格式(格式字符串"yyyy-MM-dd'T 'HH:mm:ss. SSSZ");对于反序列化,默认使用ISO-8601和RFC-1123
推荐配置:

@Configuration
public class JacksonConfig {

    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper()
            .setAnnotationIntrospector(new JacksonAnnotationIntrospector())
            .registerModule(new JavaTimeModule())
            .setDateFormat(new StdDateFormat())
            .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    }

}}
序列化日期和时间对象的示例:

  • 第1次月5日第1次月:2018年11月21日
  • 一个月六个月一个月:11:13:13.274
  • 一个月七个月一个月:2018年11月21日11:13:13.274
  • 月8日星期一:2018年11月21日星期一11:13:13.274 + 01:00
    • 编辑**:独立依赖项(已传递包含在spring-boot-starter-web中):
  • com.fasterxml.jackson.core:jackson-annotations
  • x1米11米1x
  • com.fasterxml.jackson.datatype:jackson-datatype-jsr310
k97glaaz

k97glaaz2#

尝试对created_at字段使用@JsonFormat。

@JsonFormat(pattern="yyyy-MM-dd")
@DateTimeFormat(iso = DateTimeFormat.ISO.TIME)
private LocalDateTime created_at;
xggvc2p6

xggvc2p63#

您需要在spring中添加转换器和寄存器,例如baeldung.com/spring-mvc-custom-data-binder

jfgube3f

jfgube3f4#

您可以将PaymentTransactionsDTO“created_at”属性键入为字符串,然后使用转换器将该字符串转换为LocalDate(实体“PaymentTransactionsDTO”的created_at属性类型)

@Component
public class PaymentTransactionsConverter implements Converter<PaymentTransactionsDTO, PaymentTransactions> {

    @Override
    public PaymentTransactions convert(PaymentTransactionsDTO paymentTransactionsDTO) {

        PaymentTransactions paymentTransactions = new PaymentTransactions();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        ...

        paymentTransactions.setCreated_at(LocalDate.parse(paymentTransactionsDTO.getCreated_at(), formatter));

        return paymentTransactions;
    }
}
enxuqcxy

enxuqcxy5#

定义为LocalDateTime的日期被序列化为如下所示的数组:

"timestamp": [
    2023,
    2,
    15,
    10,
    30,
    45,
    732425200
],

因此,按照Peter Walser的回答,并使用that主题的一些代码,下面是我在www.example.com中所做的WebConfig.java:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

  // other configs

  @Override
  public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    WebMvcConfigurer.super.extendMessageConverters(converters);
    converters.add(new MappingJackson2HttpMessageConverter(
        new Jackson2ObjectMapperBuilder()
            .dateFormat(new StdDateFormat())
            .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .build()));
  }

}

现在一切都好了:

"timestamp": "2023-02-15T10:32:06.5170689",

尝试玩一些Jackson建设者属性,希望它有帮助。

相关问题