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.windcentrale.internal.dto;
15 import java.lang.reflect.Type;
16 import java.time.Instant;
17 import java.time.ZoneId;
18 import java.time.ZonedDateTime;
19 import java.util.List;
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.eclipse.jdt.annotation.Nullable;
25 import com.google.gson.FieldNamingPolicy;
26 import com.google.gson.Gson;
27 import com.google.gson.GsonBuilder;
28 import com.google.gson.JsonDeserializationContext;
29 import com.google.gson.JsonDeserializer;
30 import com.google.gson.JsonElement;
31 import com.google.gson.JsonParseException;
32 import com.google.gson.JsonPrimitive;
33 import com.google.gson.JsonSerializationContext;
34 import com.google.gson.JsonSerializer;
35 import com.google.gson.reflect.TypeToken;
38 * The {@link WindcentraleGson} class provides a {@link Gson} instance configured for (de)serializing all Windcentrale
41 * @author Wouter Born - Initial contribution
44 public class WindcentraleGson {
46 public static final Gson GSON = new GsonBuilder()
47 .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
48 .registerTypeAdapter(Windmill.class, new WindmillConverter())
49 .registerTypeAdapter(ZonedDateTime.class, new ZonedDateTimeConverter()) //
52 public static final Type LIVE_DATA_RESPONSE_TYPE = new TypeToken<Map<Windmill, WindmillStatus>>() {
55 public static final Type PROJECTS_RESPONSE_TYPE = new TypeToken<List<Project>>() {
58 private static class WindmillConverter implements JsonSerializer<Windmill>, JsonDeserializer<Windmill> {
60 public JsonElement serialize(Windmill src, Type typeOfSrc, JsonSerializationContext context) {
61 return new JsonPrimitive(src.getProjectCode());
65 public @Nullable Windmill deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
66 throws JsonParseException {
67 return Windmill.fromProjectCode(json.getAsString());
71 private static class ZonedDateTimeConverter
72 implements JsonSerializer<ZonedDateTime>, JsonDeserializer<ZonedDateTime> {
74 public JsonElement serialize(ZonedDateTime src, Type typeOfSrc, JsonSerializationContext context) {
75 return new JsonPrimitive(src.toEpochSecond());
79 public @Nullable ZonedDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
80 throws JsonParseException {
81 return ZonedDateTime.ofInstant(Instant.ofEpochSecond(json.getAsLong()), ZoneId.systemDefault());