[英]Problem with formatting LocalDateTime with org.json library
我在使用org.json
庫將對象序列化為 JSON 時org.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
。 如何使用org.json
在 JSON 字符串中定義LocalDateTime
的格式?
在Java 中的 JSON 中,似乎對日期/時間格式的支持並不多。
要自定義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;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.