[英]How to deserialise JSON datetime with nanosecond precision using gson
我正在嘗試使用gson反序列化一個JSON對象,但在日期方面遇到問題。 日期從JSON對象反序列化,但由於JSON對象中的值以納秒為單位,因此我獲得的值略微偏離預期值。
請參閱以下代碼
JSONClass
public class JSONClass {
private Date timestamp;
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
}
主要
public class GsonTestApplication {
public static void main(String[] args) {
final Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss.SSS").create();
final String responseJSON = "{ \"timestamp\":\"2017-11-09 11:07:20.079364+00\" }";
final JSONClass foo = gson.fromJson(responseJSON, new TypeToken<JSONClass>(){}.getType());
System.out.println(foo.getTimestamp().toString());
}
}
應用程序的輸出是
Thu Nov 09 11:08:39 GMT 2017
當我期待它
Thu Nov 09 11:07:20 GMT 2017
我不關心納秒精度,所以我很高興被截斷,但由於我無法控制JSON格式,我不確定最好的方法。
如何讓gson正確地反序列化日期?
這是Date
可用精度的問題,對於Java 8,最好使用LocalDateTime
。 這也意味着你需要一個TypeAdapter
因為Gson與LocalDateTime
不能很好地協同工作。 需要在Gson中注冊此類型適配器,以從String
反序列化(並可能序列化) LocalDateTime
對象。
像下面這樣的東西應該給你你需要的東西。
JSONClass
public class JSONClass {
private LocalDateTime timestamp;
public LocalDateTime getTimestamp() {
return timestamp;
}
public void setTimestamp(LocalDateTime timestamp) {
this.timestamp = timestamp;
}
}
LocalDateTimeDeserialiser
static class LocalDateTimeDeserializer implements JsonDeserializer<LocalDateTime> {
private DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
LocalDateTimeDeserializer(String datePattern) {
this.formatter = DateTimeFormatter.ofPattern(datePattern);
}
@Override
public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return LocalDateTime.parse(json.getAsString(), formatter);
}
主要
public class GsonTestApplication {
public static void main(String[] args) {
final Gson gson = new GsonBuilder().(LocalDateTime.class, new LocalDateTimeDeserializer("yyyy-MM-dd HH:mm:ss.SSSSSSx")).create();
final String responseJSON = "{ \"timestamp\":\"2017-11-09 11:07:20.079364+00\" }";
final JSONClass foo = gson.fromJson(responseJSON, new TypeToken<JSONClass>(){}.getType());
System.out.println(foo.getTimestamp().toString());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.