2 * Pulled from Stack Overflow answer located here: http://stackoverflow.com/a/11272452
3 * and placed in an appropriate package within this library.
5 package org.openhab.binding.lametrictime.api.common.impl.typeadapters.imported;
7 import java.io.IOException;
8 import java.io.ObjectStreamException;
10 import com.google.gson.Gson;
11 import com.google.gson.JsonElement;
12 import com.google.gson.TypeAdapter;
13 import com.google.gson.TypeAdapterFactory;
14 import com.google.gson.reflect.TypeToken;
15 import com.google.gson.stream.JsonReader;
16 import com.google.gson.stream.JsonWriter;
18 public abstract class CustomizedTypeAdapterFactory<C> implements TypeAdapterFactory
20 private final Class<C> customizedClass;
22 public CustomizedTypeAdapterFactory(Class<C> customizedClass)
24 this.customizedClass = customizedClass;
28 @SuppressWarnings("unchecked") // we use a runtime check to guarantee that 'C' and 'T' are equal
29 public final <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type)
31 return type.getRawType() == customizedClass
32 ? (TypeAdapter<T>)customizeMyClassAdapter(gson, (TypeToken<C>)type)
36 private TypeAdapter<C> customizeMyClassAdapter(Gson gson, TypeToken<C> type)
38 final TypeAdapter<C> delegate = gson.getDelegateAdapter(this, type);
39 final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
40 return new TypeAdapter<C>()
43 public void write(JsonWriter out, C value) throws IOException
45 JsonElement tree = delegate.toJsonTree(value);
46 beforeWrite(value, tree);
47 elementAdapter.write(out, tree);
51 public C read(JsonReader in) throws IOException
53 JsonElement tree = elementAdapter.read(in);
56 throw new IOException("null reader");
58 return delegate.fromJsonTree(tree);
64 * Override this to muck with {@code toSerialize} before it is written to
65 * the outgoing JSON stream.
67 protected void beforeWrite(C source, JsonElement toSerialize)
72 * Override this to muck with {@code deserialized} before it parsed into the
75 protected void afterRead(JsonElement deserialized)