当前位置: 首页 > 知识库问答 >
问题:

Spring Boot中的LocalDateTime格式

潘英豪
2023-03-14
spring.jackson.serialization.write-dates-as-timestamps=false

对于Application.Property,我的模型类如下所示:

package bookrental.model.book;

import bookrental.model.account.User;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.util.ISO8601DateFormat;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import lombok.*;

import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.Date;

@Entity
@Getter
@Setter
@EqualsAndHashCode
@AllArgsConstructor
@NoArgsConstructor
public class BookRentals {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    @OneToOne
    private Book book;
    @OneToOne
    private User user;
    @JsonFormat(pattern = ("yyyy/MM/dd HH:mm:ss"))
    @JsonSerialize(using = LocalDateTimeSerializer.class)
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    private LocalDateTime dateOfRental;

    public BookRentals(Book book, User user) {
        this.book = book;
        this.user = user;
    }

}

我是这样设定时间的:

private BookRentals prepareBookToRent(int userID, Book book) {
        BookRentals bookRentals = new BookRentals(book, new User(userID));
        bookRentals.setDateOfRental(LocalDateTime.now());
        return bookRentals;
    }

我添加了依赖项:

<dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
            <version>2.9.7</version>
        </dependency>
[
    {
        "book": {
            "author": "Henryk Sienkiewicz",
            "category": "powieść historyczna",
            "id": 1,
            "title": "Krzyżacy"
        },
        "class": "bookrental.model.book.BookRentals",
        "dateOfRental": {
            "class": "java.time.LocalDateTime",
            "dayOfMonth": 19,
            "dayOfWeek": "WEDNESDAY",
            "dayOfYear": 353,
            "hour": 0,
            "minute": 13,
            "month": "DECEMBER",
            "monthValue": 12,
            "nano": 758649300,
            "second": 8,
            "year": 2018
        },
        "id": 1,
        "user": {
            "id": 2,
            "name": "piotri",
            "password": "123"
        }
    }
]

我没有尝试类的解决方案,因为我不知道应该把它们放进什么包中。//按照Erik的建议进行编辑,pom.xml如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.book.rental.piotrek</groupId>
<artifactId>BookRental</artifactId>
<version>1.0-SNAPSHOT</version>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>8</source>
                <target>8</target>
            </configuration>
        </plugin>
    </plugins>
</build>

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


<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.16.22</version>
    </dependency>
    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
    </dependency>
    <dependency>
        <groupId>net.sf.flexjson</groupId>
        <artifactId>flexjson</artifactId>
        <version>2.1</version>
    </dependency>
</dependencies>

</project>

升级不起作用。JSON:

[
    {
        "book": {
            "author": "Henryk Sienkiewicz",
            "category": "powieść historyczna",
            "id": 1,
            "title": "Krzyżacy"
        },
        "dateOfRental": {
            "dayOfMonth": 19,
            "dayOfWeek": "WEDNESDAY",
            "dayOfYear": 353,
            "hour": 11,
            "minute": 22,
            "month": "DECEMBER",
            "monthValue": 12,
            "nano": 884499000,
            "second": 17,
            "year": 2018
        },
        "id": 7,
        "user": {
            "id": 5,
            "name": "admin",
            "password": "123"
        }
    }
]

帐簿租金:

package bookrental.model.book;

import bookrental.model.account.User;
import lombok.*;

import javax.persistence.*;
import java.time.LocalDateTime;

@Entity
@Getter
@Setter
@EqualsAndHashCode
@AllArgsConstructor
@NoArgsConstructor
public class BookRentals {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    @OneToOne
    private Book book;
    @OneToOne
    private User user;
    private LocalDateTime dateOfRental;

    public BookRentals(Book book, User user) {
        this.book = book;
        this.user = user;
    }
}
    package bookrental.service.account;

    import bookrental.model.book.BookRentals;
    import bookrental.repository.book.BookRentalsRepository;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;

    import java.util.List;

    @Service
    public class UserRentalsService {

        private final BookRentalsRepository bookRentalsRepository;

        @Autowired
        public UserRentalsService(BookRentalsRepository bookRentalsRepository) {
            this.bookRentalsRepository = bookRentalsRepository;
        }

        public List<BookRentals> findUserRentalsByGivenID(int userID) {
            return bookRentalsRepository.getUserRentalsByGivenID(userID);
        }
    }


package bookrental.controller.account;

import bookrental.model.book.BookRentals;
import bookrental.service.account.UserRentalsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserRentalsController {

    private final UserRentalsService userRentalsService;

    @Autowired
    public UserRentalsController(UserRentalsService userRentalsService) {
        this.userRentalsService = userRentalsService;
    }

    @GetMapping("books/rentals/{userID}")
    public List<BookRentals> findUserRentalsByGivenID(@PathVariable int userID) {
        return userRentalsService.findUserRentalsByGivenID(userID);
    }
}
package bookrental.service.book.rentals;

import bookrental.model.account.User;
import bookrental.model.book.Book;
import bookrental.model.book.BookRentals;
import bookrental.repository.account.UserRepository;
import bookrental.repository.book.BookRepository;
import bookrental.repository.book.BookRentalsRepository;
import flexjson.JSONSerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class BookRentalService {

    private final UserRepository userRepository;
    private final BookRepository bookRepository;
    private final BookRentalsRepository bookRentalsRepository;

    @Autowired
    public BookRentalService(BookRepository bookRepository, BookRentalsRepository bookRentalsRepository, UserRepository userRepository) {
        this.bookRepository = bookRepository;
        this.bookRentalsRepository = bookRentalsRepository;
        this.userRepository = userRepository;
    }

    ....

    public ResponseEntity<String> findAllRentals() {
        List<BookRentals> rentedBooks = new ArrayList<>();
        bookRentalsRepository.findAll().forEach(rentedBooks::add);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json; charset=utf-8");
        return new ResponseEntity<>(new JSONSerializer().exclude("book.class")
                .exclude("book.available")
                .exclude("dateOfReturn")
                .exclude("*.class")
                .exclude("user.amountOfCashToPay")
                .exclude("password")
                .serialize(rentedBooks), headers, HttpStatus.OK);
    }

}

共有1个答案

龚振
2023-03-14

这是一个使用Spring 2.1.1的更新示例:

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

@SpringBootApplication
class PipilamApplication {
    public static void main(String[] args) {
        SpringApplication.run(PipilamApplication.class, args);
    }
}

@RestController
class Controller {

    @GetMapping("/demo")
    public Demo demo() {
        return new Demo("pipilam",LocalDateTime.now());
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
class Demo {
    String name;
    LocalDateTime dateTime;
}

连接到http://localhost:8080/demo会得到以下输出:

{"name":"pipilam","dateTime":"2018-12-19T20:16:12.780268"}

不需要配置或注释。我之前的回答被否决了。这是我使用的pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.stackoverflow</groupId>
    <artifactId>pipilam</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>pipilam</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
 类似资料:
  • 将 LocalDateTime 转换为 LocalDateTime(以 UTC 为单位)。 我在网上搜索。但没有找到解决方案

  • 问题内容: 我在Spring Boot应用程序中格式化Java 8 LocalDateTime时遇到一个小问题。对于“正常”日期,我没有问题,但是LocalDateTime字段转换为以下内容: 虽然我想将其转换为: 我的代码如下所示: 但是以上任何一个注释均无法正常工作,日期的格式仍与上面一样。建议欢迎! 问题答案: 更新 :Spring Boot 2.x不再需要此配置。我在这里写了一个最新的答案

  • 我在Spring Boot应用程序中格式化Java8LocalDateTime时遇到了一个小问题。对于“正常”日期,我没有问题,但LocalDateTime字段将转换为以下内容: 而我想将其转换为以下内容: 我的代码如下所示: 但是上面的任何一个注解都不起作用,日期会一直按照上面的格式设置。欢迎提出建议!

  • 我在我的模型中使用LocalDateTime,在包括LocalDateTimeDeserializer之后,将bean字段转换为 包括 属性在SpringBoot的应用程序中。属性文件,应用程序最终能够反序列化JSON并正确显示如下内容:, 但是,当我进行测试时,它会忽略WRITE_DATES_AS_TIMESTAMPS标志,我猜它会为上面相同的字符串日期生成一个输出, 请注意,在测试资源文件夹中

  • 我有这个简单的代码: 然后我将得到以下异常: 如何解决这个问题?

  • 我试图从LocaLDateTime创建json对象,但由于某种原因,它创建json的方式如下:查找issueAt和expireAt键 json{“userid”:0,“deviceid”:0,“refreshtoken”:“93180548-23B3-4D1B-8B5B-A105B7CFF7F9”,“issuedat”:{“年份”:2021,“月份值”:10,“月份日”:27,“小时”:9,“分钟