使用GSON在Spring Boot中使用多种日期格式

时间:2019-06-13 16:37:20

标签: spring-boot gson

我正在使用GSON的弹簧靴。我有一个具有2个具有不同日期格式的日期字段的Bean

  1. yyyy-MM-dd hh:mm
  2. yyyy-MM-dd

使用我可以设置的GSON弹簧靴

spring.gson.date-format= yyyy-MM-dd hh:mm

但是这希望第二个字段遵循yyyy-MM-dd hh:mm。

我知道使用jackson可以使用@JsonFormat批注指定其他日期格式,我们可以在Spring中使用GSON进行类似的操作

1 个答案:

答案 0 :(得分:1)

您可以尝试自定义JsonSerializerJsonDeserializer来自定义bean的字段序列化/反序列化,简单的例子:

pom.xml 依赖项:

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <!-- Exclude the default Jackson dependency -->
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-json</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.4</version>
        </dependency>
    </dependencies>

DemoApplication.lava

package com.example.demo;

import com.google.gson.*;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        Gson gson = SpringApplication.run(DemoApplication.class, args).getBean(Gson.class);

        // json entity with timestamp -> dateFirst and dateSecond
        String jsonSomeEntity =
                   "{" +
                        "\"dateFirst\": \"" + Timestamp.valueOf(LocalDateTime.now()).getTime() + "\"," +
                        "\"dateSecond\": \"" + Timestamp.valueOf(LocalDateTime.now()).getTime() + "\"" +
                    "}";

        SomeEntity someEntity = gson.fromJson(jsonSomeEntity, SomeEntity.class);

        jsonSomeEntity = gson.toJson(someEntity);

        System.out.println(jsonSomeEntity);
    }

    private static final DateTimeFormatter FORMATTER_FIRST = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
    private static final DateTimeFormatter FORMATTER_SECOND = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    @Bean
    GsonBuilder gsonBuilder() {
        return new GsonBuilder()

                // SomeEntity to json
                // dateFirst  -> LocalDateTime -> timestamp
                // dateSecond -> LocalDate     -> timestamp
                .registerTypeAdapter(SomeEntity.class, (JsonSerializer<SomeEntity>) (entity, type, context) -> {
                    JsonObject jsonObject = new JsonObject();

                    long dateFirstTimeStamp = Timestamp.valueOf(entity.getDateFirst()).getTime();
                    long dateSecondTimeStamp = Timestamp.valueOf(entity.getDateSecond().atStartOfDay()).getTime();

                    jsonObject.addProperty("dateFirst", dateFirstTimeStamp);
                    jsonObject.addProperty("dateSecond", dateSecondTimeStamp);

                    return jsonObject;
                })

                // json ot SomeEntity
                // dateFirst  -> timestamp -> LocalDateTime -> "yyyy-MM-dd HH:mm"
                // dateSecond -> timestamp -> LocalDate     -> "yyyy-MM-dd"
                .registerTypeAdapter(SomeEntity.class, (JsonDeserializer<SomeEntity>) (json, type, context) -> {
                    long dateFirstTimeStamp = ((JsonObject) json).get("dateFirst").getAsLong();
                    long dateSecondTimeStamp = ((JsonObject) json).get("dateSecond").getAsLong();

                    LocalDateTime LocalDateTimeFirst = new Timestamp(dateFirstTimeStamp).toLocalDateTime();
                    LocalDate localDateSecond = new Timestamp(dateSecondTimeStamp).toLocalDateTime().toLocalDate();

                    String dateFirstFormatted = FORMATTER_FIRST.format(LocalDateTimeFirst);
                    String dateSecondFormatted = FORMATTER_SECOND.format(localDateSecond);

                    return new SomeEntity(
                            LocalDateTime.parse(dateFirstFormatted, FORMATTER_FIRST),
                            LocalDate.parse(dateSecondFormatted, FORMATTER_SECOND));
                });
    }

    public static class SomeEntity {
        private final LocalDateTime dateFirst;
        private final LocalDate dateSecond;

        public SomeEntity(LocalDateTime dateFirst, LocalDate dateSecond) {
            this.dateFirst = dateFirst;
            this.dateSecond = dateSecond;
        }

        public LocalDateTime getDateFirst() {
            return dateFirst;
        }

        public LocalDate getDateSecond() {
            return dateSecond;
        }
    }

}