我在使用 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
的格式?
最佳答案
在 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;
}
}
}
关于java - 使用 org.json 库格式化 LocalDateTime 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59894573/