【问题标题】:Convert java.util.Date to json format将 java.util.Date 转换为 json 格式
【发布时间】:2018-03-06 01:16:27
【问题描述】:

我必须将我的 POJO 转换为 JSON 字符串才能发送到客户端代码。

但是,当我这样做时,我的 POJO 中的 java.util.Date 字段(具有值“2107-06-05 00:00:00.0”)被翻译为“1496592000000”,我认为这是一个时代以来的时间。我希望它在 Json 中更具可读性,可能是 'DD/MM/YYYY' 格式。

我在 Spring Boot 应用程序中使用 RestEasy 控制器来处理 Java 对象到 JSON 的转换。

有什么线索吗?

【问题讨论】:

  • 您是否考虑过使用日期格式化程序,例如 SimpleDateFormat?
  • 发布代码....
  • @AkshayLokur 我认为您可以使用@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ") 注释您的 POJO 字段,或者如果您希望它在全球范围内工作,可以使用 mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); 设置您的杰克逊对象映射器
  • 请注意,这两种格式是不同的:时间戳是一个即时,即时间线上的一个点。 DD/mm/yyyy 是 本地日期,即 24 小时(通常)较长的时间段,它只能与给定特定时区的时间戳相关。您的应用程序可能需要其中一个,但不要认为它们是等效的。
  • @jan.vdbergh 这完全取决于您要表示的内容:如果您表示某事发生的时间,例如一个日志事件,时间戳是正确的。如果您试图表示人工输入的日期,例如生日,时间戳不正确:您的生日不会因为您前往不同的时区而改变。

标签: java json spring-boot jackson resteasy


【解决方案1】:

RestEasy 通过 Jackson 支持 JSON,因此您可以通过多种方式处理 Date 序列化。

1。 @JsonFormat 注解

如果您想格式化特定字段 - 只需将 @JsonFormat 注释添加到您的 POJO。

public class TestPojo {

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
    public Date testDate;
}

2。杰克逊房产

如果您想全局设置Date 序列化格式 - 您必须调整 Jackson 配置属性。例如。对于application.properties 文件格式。

第一个禁用WRITE_DATES_AS_TIMESTAMPS serialization feature

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

第二个定义日期格式:

spring.jackson.date-format=dd-MM-yyyy

或者,对于application.yml 文件格式:

spring:
  jackson:
    date-format: "dd-MM-yyyy"
    serialization:
      write_dates_as_timestamps: false

3。自定义序列化器

如果您想完全控制序列化 - 您必须实现自定义 StdSerializer

public class CustomDateSerializer extends StdSerializer<Date> {

    private SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");

    public CustomDateSerializer() {
        this(null);
    }

    public CustomDateSerializer(Class t) {
        super(t);
    }

    @Override
    public void serialize(Date date, JsonGenerator generator, SerializerProvider provider) 
        throws IOException, JsonProcessingException {

        generator.writeString(formatter.format(date));
    }
}

然后和@JsonSerialize一起使用:

public class TestPojo {

    @JsonSerialize(using = CustomDateSerializer.class)
    public Date testDate;
}

【讨论】:

    猜你喜欢
    • 2018-09-23
    • 2020-11-02
    • 2012-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-10
    • 2011-08-29
    • 2019-08-03
    相关资源
    最近更新 更多