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.api.common.impl.typeadapters.imported;
19 import java.io.IOException;
20 import java.io.ObjectStreamException;
22 import com.google.gson.Gson;
23 import com.google.gson.JsonElement;
24 import com.google.gson.TypeAdapter;
25 import com.google.gson.TypeAdapterFactory;
26 import com.google.gson.reflect.TypeToken;
27 import com.google.gson.stream.JsonReader;
28 import com.google.gson.stream.JsonWriter;
30 public abstract class CustomizedTypeAdapterFactory<C> implements TypeAdapterFactory
32 private final Class<C> customizedClass;
34 public CustomizedTypeAdapterFactory(Class<C> customizedClass)
36 this.customizedClass = customizedClass;
40 @SuppressWarnings("unchecked") // we use a runtime check to guarantee that 'C' and 'T' are equal
41 public final <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type)
43 return type.getRawType() == customizedClass
44 ? (TypeAdapter<T>)customizeMyClassAdapter(gson, (TypeToken<C>)type)
48 private TypeAdapter<C> customizeMyClassAdapter(Gson gson, TypeToken<C> type)
50 final TypeAdapter<C> delegate = gson.getDelegateAdapter(this, type);
51 final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
52 return new TypeAdapter<C>()
55 public void write(JsonWriter out, C value) throws IOException
57 JsonElement tree = delegate.toJsonTree(value);
58 beforeWrite(value, tree);
59 elementAdapter.write(out, tree);
63 public C read(JsonReader in) throws IOException
65 JsonElement tree = elementAdapter.read(in);
68 throw new IOException("null reader");
70 return delegate.fromJsonTree(tree);
76 * Override this to muck with {@code toSerialize} before it is written to
77 * the outgoing JSON stream.
79 protected void beforeWrite(C source, JsonElement toSerialize)
84 * Override this to muck with {@code deserialized} before it parsed into the
87 protected void afterRead(JsonElement deserialized)