]> git.basschouten.com Git - openhab-addons.git/blob
0591540f4523311c2fe07b5215ae70cb80767230
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.energidataservice.internal.api.serialization;
14
15 import java.lang.reflect.Type;
16 import java.time.Instant;
17 import java.time.format.DateTimeParseException;
18
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
21
22 import com.google.gson.JsonDeserializationContext;
23 import com.google.gson.JsonDeserializer;
24 import com.google.gson.JsonElement;
25 import com.google.gson.JsonParseException;
26
27 /**
28  * The {@link InstantDeserializer} converts a formatted UTC string to {@link Instant}.
29  *
30  * @author Jacob Laursen - Initial contribution
31  */
32 @NonNullByDefault
33 public class InstantDeserializer implements JsonDeserializer<Instant> {
34
35     @Override
36     public @Nullable Instant deserialize(JsonElement element, Type arg1, JsonDeserializationContext arg2)
37             throws JsonParseException {
38         String content = element.getAsString();
39         try {
40             // When writing this, the format of the provided UTC strings lacks the trailing 'Z'.
41             // In case this would be fixed in the future, gracefully support both with and without this.
42             return Instant.parse(content.endsWith("Z") ? content : content + "Z");
43         } catch (DateTimeParseException e) {
44             throw new JsonParseException("Could not parse as Instant: " + content, e);
45         }
46     }
47 }