diff options
Diffstat (limited to 'gson/src/main/java/org/onap/policy/common/gson/ZonedDateTimeTypeAdapter.java')
-rw-r--r-- | gson/src/main/java/org/onap/policy/common/gson/ZonedDateTimeTypeAdapter.java | 45 |
1 files changed, 14 insertions, 31 deletions
diff --git a/gson/src/main/java/org/onap/policy/common/gson/ZonedDateTimeTypeAdapter.java b/gson/src/main/java/org/onap/policy/common/gson/ZonedDateTimeTypeAdapter.java index 147fb03d..928fae95 100644 --- a/gson/src/main/java/org/onap/policy/common/gson/ZonedDateTimeTypeAdapter.java +++ b/gson/src/main/java/org/onap/policy/common/gson/ZonedDateTimeTypeAdapter.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,45 +20,28 @@ package org.onap.policy.common.gson; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonToken; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; /** * GSON Type Adapter for "ZonedDateTime" fields, that uses the standard * ISO_ZONED_DATE_TIME formatter. */ -public class ZonedDateTimeTypeAdapter extends TypeAdapter<ZonedDateTime> { - private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ISO_ZONED_DATE_TIME; +public class ZonedDateTimeTypeAdapter extends StringTypeAdapter<ZonedDateTime> { - @Override - public ZonedDateTime read(JsonReader in) throws IOException { - try { - if (in.peek() == JsonToken.NULL) { - in.nextNull(); - return null; - } else { - return ZonedDateTime.parse(in.nextString(), FORMATTER); - } - - } catch (DateTimeParseException e) { - throw new JsonParseException("invalid date", e); - } + /** + * Constructs an adapter that uses the ISO_ZONED_DATE_TIME formatter. + */ + public ZonedDateTimeTypeAdapter() { + this(DateTimeFormatter.ISO_ZONED_DATE_TIME); } - @Override - public void write(JsonWriter out, ZonedDateTime value) throws IOException { - if (value == null) { - out.nullValue(); - } else { - String text = value.format(FORMATTER); - out.value(text); - } + /** + * Constructs an adapter that uses the specified formatter for reading and writing. + * + * @param formatter date-time formatter + */ + public ZonedDateTimeTypeAdapter(DateTimeFormatter formatter) { + super("date", string -> ZonedDateTime.parse(string, formatter), value -> value.format(formatter)); } } |