Spring Boot中的LocalDateTime格式

时间:2018-12-18 23:22:25

标签: java spring spring-boot localdate

嘿,我遇到了与这里相同的问题:JSON Java 8 LocalDateTime format in Spring Boot我从那里尝试了解决方案,但它不起作用。有人可以告诉我我做错了什么吗?

我添加了

grep

至application.property 我的模型类如下:

$ show=men
$ echo -e "Alice\nBob\nCarol\nDavid" | if [[ "$show" = "men" ]]; then egrep 'Bob|David'; else egrep 'Alice|Carol'; fi
Bob
David

$ show=women
$ echo -e "Alice\nBob\nCarol\nDavid" | if [[ "$show" = "men" ]]; then egrep 'Bob|David'; else egrep 'Alice|Carol'; fi
Alice
Carol

我这样设定时间:

spring.jackson.serialization.write-dates-as-timestamps=false

我添加了依赖性:

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;
    }

}

我的JSON如下所示:

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

我还应该做什么?

我没有尝试使用类的解决方案,因为我不知道应该将它们放在哪个包中。 // 编辑 在Erik的建议下,pom.xml如下所示:

<dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
            <version>2.9.7</version>
        </dependency>

升级无效。 JSON:

[
    {
        "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"
        }
    }
]

BookRentals:

<?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>

// EDIT2

嘿。偶然发现了问题的原因。我有一个类,负责为确切的用户查找确切的名词。当我去[ { "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; } } 。在/books/rentals/{userID}中,我返回ResponseEntity,因此我认为它看起来像这样。你知道如何解决吗?

List<BookRentals>

BookRentalsService

BookRentalsService

2 个答案:

答案 0 :(得分:0)

您甚至需要@JsonSerialize(using = LocalDateTimeSerializer.class)@JsonDeserialize(using = LocalDateTimeDeserializer.class)吗?

我也有完全相同的问题,也使用了jackson-datatype-jsr310依赖项。切换到init(_:)为我解决了这个问题:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-json</artifactId>
    <version>2.0.3.RELEASE</version>
</dependency>

答案 1 :(得分:0)

这是使用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"}

无需配置或注释。考虑不推荐使用my previous answer。这是我使用的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>

您可以在Github中找到该项目:https://github.com/bodiam/spring-boot-java8-json-time