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;
9 import com.google.gson.Gson;
10 import com.google.gson.JsonElement;
11 import com.google.gson.TypeAdapter;
12 import com.google.gson.TypeAdapterFactory;
13 import com.google.gson.reflect.TypeToken;
14 import com.google.gson.stream.JsonReader;
15 import com.google.gson.stream.JsonWriter;
17 public abstract class CustomizedTypeAdapterFactory<C> implements TypeAdapterFactory
19 private final Class<C> customizedClass;
21 public CustomizedTypeAdapterFactory(Class<C> customizedClass)
23 this.customizedClass = customizedClass;
27 @SuppressWarnings("unchecked") // we use a runtime check to guarantee that 'C' and 'T' are equal
28 public final <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type)
30 return type.getRawType() == customizedClass
31 ? (TypeAdapter<T>)customizeMyClassAdapter(gson, (TypeToken<C>)type)
35 private TypeAdapter<C> customizeMyClassAdapter(Gson gson, TypeToken<C> type)
37 final TypeAdapter<C> delegate = gson.getDelegateAdapter(this, type);
38 final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
39 return new TypeAdapter<C>()
42 public void write(JsonWriter out, C value) throws IOException
44 JsonElement tree = delegate.toJsonTree(value);
45 beforeWrite(value, tree);
46 elementAdapter.write(out, tree);
50 public C read(JsonReader in) throws IOException
52 JsonElement tree = elementAdapter.read(in);
54 return delegate.fromJsonTree(tree);
60 * Override this to muck with {@code toSerialize} before it is written to
61 * the outgoing JSON stream.
63 protected void beforeWrite(C source, JsonElement toSerialize)
68 * Override this to muck with {@code deserialized} before it parsed into the
71 protected void afterRead(JsonElement deserialized)