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
14 * Pulled from Stack Overflow answer located here: http://stackoverflow.com/a/11272452
15 * and placed in an appropriate package within this library.
17 package org.openhab.binding.lametrictime.internal.api.common.impl.typeadapters.imported;
19 import java.io.IOException;
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.eclipse.jdt.annotation.Nullable;
24 import com.google.gson.Gson;
25 import com.google.gson.JsonElement;
26 import com.google.gson.TypeAdapter;
27 import com.google.gson.TypeAdapterFactory;
28 import com.google.gson.reflect.TypeToken;
29 import com.google.gson.stream.JsonReader;
30 import com.google.gson.stream.JsonWriter;
33 * Abstract type adapter factory.
35 * @author Gregory Moyer - Initial contribution
38 public abstract class CustomizedTypeAdapterFactory<C> implements TypeAdapterFactory {
39 private final Class<C> customizedClass;
41 public CustomizedTypeAdapterFactory(Class<C> customizedClass) {
42 this.customizedClass = customizedClass;
46 @SuppressWarnings("unchecked") // we use a runtime check to guarantee that 'C' and 'T' are equal
48 public final <T> TypeAdapter<T> create(@Nullable Gson gson, @Nullable TypeToken<T> type) {
49 return type.getRawType() == customizedClass
50 ? (TypeAdapter<T>) customizeMyClassAdapter(gson, (TypeToken<C>) type)
54 private TypeAdapter<C> customizeMyClassAdapter(@Nullable Gson gson, TypeToken<C> type) {
55 final TypeAdapter<C> delegate = gson.getDelegateAdapter(this, type);
56 final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
57 return new TypeAdapter<C>() {
59 public void write(JsonWriter out, @Nullable C value) throws IOException {
60 JsonElement tree = delegate.toJsonTree(value);
61 beforeWrite(value, tree);
62 elementAdapter.write(out, tree);
66 public @Nullable C read(JsonReader in) throws IOException {
67 JsonElement tree = elementAdapter.read(in);
70 throw new IOException("null reader");
72 return delegate.fromJsonTree(tree);
78 * Override this to muck with {@code toSerialize} before it is written to
79 * the outgoing JSON stream.
81 protected void beforeWrite(C source, JsonElement toSerialize) {
85 * Override this to muck with {@code deserialized} before it parsed into the
88 protected void afterRead(@Nullable JsonElement deserialized) {