我使用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
中却没有找到类似的注释。如何使用LocalDateTime
定义JSON字符串中org.json
的格式?
在JSON in Java中,似乎日期/时间格式没有太多支持。
要自定义LocalDateTime
字段的格式,我们可以使用1. @JSONPropertyIgnore忽略要序列化的原始吸气剂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;
}
}
}