2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.nest.internal.sdm.dto;
15 import java.lang.reflect.Type;
16 import java.time.ZonedDateTime;
17 import java.time.format.DateTimeFormatter;
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
22 import com.google.gson.Gson;
23 import com.google.gson.GsonBuilder;
24 import com.google.gson.JsonDeserializationContext;
25 import com.google.gson.JsonDeserializer;
26 import com.google.gson.JsonElement;
27 import com.google.gson.JsonParseException;
28 import com.google.gson.JsonPrimitive;
29 import com.google.gson.JsonSerializationContext;
30 import com.google.gson.JsonSerializer;
33 * The {@link SDMGson} class provides a {@link Gson} instance configured for (de)serializing all SDM and Pub/Sub data
36 * @author Wouter Born - Initial contribution
39 public class SDMGson {
41 public static final Gson GSON = new GsonBuilder()
42 .registerTypeAdapter(SDMResourceName.class, new SDMResourceNameConverter()) //
43 .registerTypeAdapter(ZonedDateTime.class, new ZonedDateTimeConverter()) //
46 private static class SDMResourceNameConverter
47 implements JsonSerializer<SDMResourceName>, JsonDeserializer<SDMResourceName> {
50 public JsonElement serialize(SDMResourceName src, Type typeOfSrc, JsonSerializationContext context) {
51 return new JsonPrimitive(src.toString());
55 public @Nullable SDMResourceName deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
56 throws JsonParseException {
57 return new SDMResourceName(json.getAsString());
61 private static class ZonedDateTimeConverter
62 implements JsonSerializer<ZonedDateTime>, JsonDeserializer<ZonedDateTime> {
63 private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ISO_DATE_TIME;
66 public JsonElement serialize(ZonedDateTime src, Type typeOfSrc, JsonSerializationContext context) {
67 return new JsonPrimitive(FORMATTER.format(src));
71 public @Nullable ZonedDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
72 throws JsonParseException {
73 return ZonedDateTime.parse(json.getAsString());