【问题标题】:Problem with formatting LocalDateTime with org.json library使用 org.json 库格式化 LocalDateTime 的问题
【发布时间】:2020-01-24 10:26:58
【问题描述】:

我在使用 org.json 库将对象序列化为 JSON 时遇到问题。

在我的代码中:

String resultStr = new JSONObject(result).toString();

在结果对象中有两个LocalDateTime类型的字段:

private LocalDateTime startDate;
private LocalDateTime stopDate;

在变量resultStr 中,我得到了以下格式的日期:

2020-01-23T14:13:30.121205

我想要这个 ISO 格式:

2016-07-14T07:58:08.158Z

我知道在 Jackson 中有一个注释 @JsonFormat,但我在 org.json 中没有找到类似的东西。如何用org.json在JSON字符串中定义LocalDateTime的格式?

【问题讨论】:

  • 使用ZonedDateTime 而不是LocalDateTime
  • 您是否尝试将您的 LocalDateTime 对象转换为 ISO 那样 (DateTimeFormatter.BASIC_ISO_DATE) .format(startDate));
  • @YCF_L ZonedDateTime in json 被格式化为“2020-01-23T14:13:30.121Z[UTC]”,但我想要像“2016-07-14T07:58:08.158Z”这样的格式最后是毫秒和 Z。
  • 试试OffsetDateTime
  • @Hatice 问题是我不知道应该在哪里使用 DateTimeFormatter 和 org.json,我找不到这种可能性。

标签: java json org.json


【解决方案1】:

JSON in Java中,似乎对日期/时间格式的支持并不多。

要自定义LocalDateTime字段的格式,我们可以使用
1.@JSONPropertyIgnore忽略原来要序列化的getter
2. @JSONPropertyName 用忽略的字段名称注释一个新的getter,它返回所需的格式化日期字符串,如下所示:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import org.json.JSONObject;
import org.json.JSONPropertyIgnore;
import org.json.JSONPropertyName;

public class CustomizeLocalDateTimeFormatInOrgJson {
    public static void main(String[] args) {
        Result result = new Result(LocalDateTime.now(), LocalDateTime.now());
        String resultStr = new JSONObject(result).toString();
        System.out.println(resultStr);
    }

    public static class Result {
        DateTimeFormatter customDateTimeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssS'Z'");
        private LocalDateTime startDate;

        @JSONPropertyIgnore
        public LocalDateTime getStartDate() {
            return startDate;
        }

        @JSONPropertyName("startDate")
        public String getStartDateString() {
            return customDateTimeFormat.format(startDate);
        }

        private LocalDateTime stopDate;

        @JSONPropertyIgnore
        public LocalDateTime getStopDate() {
            return stopDate;
        }

        @JSONPropertyName("stopDate")
        public String getStopDateString() {
            return customDateTimeFormat.format(stopDate);
        }

        public void setStopDate(LocalDateTime stopDate) {
            this.stopDate = stopDate;
        }

        public void setStartDate(LocalDateTime startDate) {
            this.startDate = startDate;
        }

        public Result(LocalDateTime startDate, LocalDateTime stopDate) {
            super();
            this.startDate = startDate;
            this.stopDate = stopDate;
        }
    }
}

【讨论】:

    猜你喜欢
    • 2014-10-23
    • 1970-01-01
    • 2018-07-22
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多