【发布时间】: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,我找不到这种可能性。