Example usage for com.google.gson.reflect TypeToken getRawType

List of usage examples for com.google.gson.reflect TypeToken getRawType

Introduction

In this page you can find the example usage for com.google.gson.reflect TypeToken getRawType.

Prototype

public final Class<? super T> getRawType() 

Source Link

Document

Returns the raw (non-generic) type for this type.

Usage

From source file:co.cask.cdap.common.stream.StreamEventTypeAdapter.java

License:Apache License

/**
 * Register an instance of the {@link StreamEventTypeAdapter} to the given {@link GsonBuilder}.
 * @param gsonBuilder The build to register to
 * @return The same {@link GsonBuilder} instance in the argument
 *//*ww w  .j  a  va  2  s . c  om*/
public static GsonBuilder register(GsonBuilder gsonBuilder) {
    return gsonBuilder.registerTypeAdapterFactory(new TypeAdapterFactory() {
        @Override
        @SuppressWarnings("unchecked")
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
            if (StreamEvent.class.isAssignableFrom(type.getRawType())) {
                return (TypeAdapter<T>) new StreamEventTypeAdapter(gson.getAdapter(HEADERS_TYPE));
            }
            return null;
        }
    });
}

From source file:co.forsaken.projectindigo.utils.mojangtokens.EnumTypeAdapterFactory.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from w  w  w .  j a v a2s .  c o m*/
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    if (!type.getRawType().isEnum()) {
        return null;
    }
    final Map<String, T> map = new HashMap<String, T>();
    for (T c : (T[]) type.getRawType().getEnumConstants()) {
        map.put(c.toString().toLowerCase(Locale.US), c);
    }

    return new TypeAdapter<T>() {
        @Override
        public T read(JsonReader reader) throws IOException {
            if (reader.peek() == JsonToken.NULL) {
                reader.nextNull();
                return null;
            }
            String name = reader.nextString();
            if (name == null) {
                return null;
            }
            return map.get(name.toLowerCase(Locale.US));
        }

        @Override
        public void write(JsonWriter writer, T value) throws IOException {
            if (value == null) {
                writer.nullValue();
            } else {
                writer.value(value.toString().toLowerCase(Locale.US));
            }
        }
    };
}

From source file:com.actimem.blog.gson.customtypeadapters.CustomTypeAdapterFactory.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*from ww  w .  ja va 2  s .c o m*/
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    return typeAdaptersMap.get(type.getRawType());
}

From source file:com.android.fastlibrary.util.AutoValueAdapterFactory.java

License:Apache License

@SuppressWarnings("unchecked")
@Override//ww  w.  j av  a  2s. co m
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
    Class<? super T> rawType = type.getRawType();
    if (!rawType.isAnnotationPresent(AutoGson.class)) {
        return null;
    }

    String packageName = rawType.getPackage().getName();
    String className = rawType.getName().substring(packageName.length() + 1).replace('$', '_');
    String autoValueName = packageName + ".AutoValue_" + className;

    try {
        Class<?> autoValueType = Class.forName(autoValueName);
        return (TypeAdapter<T>) gson.getAdapter(autoValueType);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("Could not load AutoValue type " + autoValueName, e);
    }
}

From source file:com.atlauncher.workers.EnumTypeAdapterFactory.java

License:Creative Commons License

@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    if (!type.getRawType().isEnum())
        return null;
    final Map<String, T> map = new HashMap<String, T>();
    for (T c : (T[]) type.getRawType().getEnumConstants()) {
        map.put(c.toString().toLowerCase(Locale.US), c);
    }/* w w  w.  j  ava  2  s. co  m*/

    return new TypeAdapter<T>() {
        @Override
        public T read(JsonReader reader) throws IOException {
            if (reader.peek() == JsonToken.NULL) {
                reader.nextNull();
                return null;
            }
            String name = reader.nextString();
            if (name == null)
                return null;
            return map.get(name.toLowerCase(Locale.US));
        }

        @Override
        public void write(JsonWriter writer, T value) throws IOException {
            if (value == null) {
                writer.nullValue();
            } else {
                writer.value(value.toString().toLowerCase(Locale.US));
            }
        }
    };
}

From source file:com.birbit.jsonapi.JsonApiDeserializer.java

License:Apache License

private T[] parseData(JsonDeserializationContext context, ParameterizedType parameterizedType,
        JsonObject jsonObject) {/*from www .jav a  2  s .com*/
    JsonElement dataElm = jsonObject.get("data");
    if (dataElm != null) {
        Type typeArg = parameterizedType.getActualTypeArguments()[0];
        if (dataElm.isJsonArray()) {
            JsonArray jsonArray = dataElm.getAsJsonArray();
            final int size = jsonArray.size();
            //                boolean isArray = typeArg instanceof GenericArrayType;
            //                if (isArray) {
            TypeToken<?> typeToken = TypeToken.get(typeArg);
            T[] result = (T[]) Array.newInstance(typeToken.getRawType().getComponentType(), size);
            for (int i = 0; i < size; i++) {
                ResourceWithIdAndType<T> resourceWithIdAndType = parseResource(jsonArray.get(i), context);
                result[i] = resourceWithIdAndType.resource;
            }
            return result;
            //                } else {
            //                    TypeToken<?> typeToken = TypeToken.get(typeArg);
            //                    T[] result = (T[]) Array.newInstance(typeToken.getRawType().getComponentType(), size);
            //                    for (int i = 0; i < size; i ++) {
            //                        ResourceWithIdAndType<T> resourceWithIdAndType = parseResource(jsonArray.get(i), context);
            //                        //noinspection unchecked
            //                        result[i] = resourceWithIdAndType.resource;
            //                    }
            //                    return result;
            //                }
        } else if (dataElm.isJsonObject()) {
            T resource = parseResource(dataElm, context).resource;
            Object[] result = (Object[]) Array.newInstance(resource.getClass(), 1);
            result[0] = resource;
            return (T[]) result;
        }
    }
    return null;
}

From source file:com.chalup.gsonadapters.JsonRootAdapterFactory.java

License:Apache License

@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    JsonRootName rootAnnotation = typeToken.getRawType().getAnnotation(JsonRootName.class);
    if (rootAnnotation == null) {
        return null;
    }/*from   w  w w .j  a  va2  s .  c om*/

    TypeAdapter<T> delegateAdapter = gson.getDelegateAdapter(this, typeToken);
    return new Adapter<T>(delegateAdapter, rootAnnotation.value());
}

From source file:com.continuuity.loom.codec.json.LowercaseEnumTypeAdapterFactory.java

License:Apache License

public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    Class<T> rawType = (Class<T>) type.getRawType();
    if (!rawType.isEnum()) {
        return null;
    }//from  ww w .  j av  a  2 s  .  com

    final Map<String, T> lowercaseToConstant = Maps.newHashMap();
    for (T constant : rawType.getEnumConstants()) {
        lowercaseToConstant.put(toLowercase(constant), constant);
    }

    return new TypeAdapter<T>() {
        public void write(JsonWriter out, T value) throws IOException {
            if (value == null) {
                out.nullValue();
            } else {
                out.value(toLowercase(value));
            }
        }

        public T read(JsonReader reader) throws IOException {
            if (reader.peek() == JsonToken.NULL) {
                reader.nextNull();
                return null;
            } else {
                String next = reader.nextString();
                return lowercaseToConstant.get(next);
            }
        }
    };
}

From source file:com.cyanogenmod.account.gcm.model.MessageTypeAdapterFactory.java

License:Apache License

@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    if (!Message.class.isAssignableFrom(type.getRawType())) {
        return null;
    }/* w w  w .j  a v a 2  s  .c o m*/

    final TypeAdapter<Message> rootAdapter = gson.getDelegateAdapter(this, TypeToken.get(Message.class));
    final TypeAdapter<PublicKeyMessage> keyExchangeAdapter = gson.getDelegateAdapter(this,
            TypeToken.get(PublicKeyMessage.class));
    final TypeAdapter<SymmetricKeyMessage> symmetricKeyAdapter = gson.getDelegateAdapter(this,
            TypeToken.get(SymmetricKeyMessage.class));
    final TypeAdapter<EncryptedMessage> secureMessageAdapter = gson.getDelegateAdapter(this,
            TypeToken.get(EncryptedMessage.class));
    final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);

    TypeAdapter<Message> result = new TypeAdapter<Message>() {
        @Override
        public void write(JsonWriter out, Message value) throws IOException {
            if (value instanceof PublicKeyMessage) {
                keyExchangeAdapter.write(out, (PublicKeyMessage) value);
            } else if (value instanceof SymmetricKeyMessage) {
                symmetricKeyAdapter.write(out, (SymmetricKeyMessage) value);
            } else if (value instanceof EncryptedMessage) {
                secureMessageAdapter.write(out, (EncryptedMessage) value);
            } else {
                JsonObject object = rootAdapter.toJsonTree(value).getAsJsonObject();
                elementAdapter.write(out, object);
            }
        }

        @Override
        public Message read(JsonReader in) throws IOException {
            JsonObject object = elementAdapter.read(in).getAsJsonObject();
            if (object.has("public_key")) {
                return keyExchangeAdapter.fromJsonTree(object);
            } else if (object.has("symmetric_key")) {
                return symmetricKeyAdapter.fromJsonTree(object);
            } else if (object.has("ciphertext")) {
                return secureMessageAdapter.fromJsonTree(object);
            } else {
                return rootAdapter.fromJsonTree(object);
            }
        }
    }.nullSafe();

    return (TypeAdapter<T>) result;
}

From source file:com.dampcake.gson.immutable.ImmutableAdapterFactory.java

License:Apache License

/**
 * @see TypeAdapterFactory#create(Gson, TypeToken) 
 *//*ww w . j a va 2  s.  c om*/
@Override
@SuppressWarnings("unchecked")
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    if (adapters.containsKey(type.getRawType())) {
        TypeAdapter delegate = getDelegate(gson, type);
        try {
            return adapters.get(type.getRawType()).getConstructor(TypeAdapter.class).newInstance(delegate);
        } catch (Exception e) {
            return null;
        }
    }
    return null;
}