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:BundleTypeAdapterFactory.java

License:Apache License

@SuppressWarnings("unchecked")
@Override// ww  w  .ja v  a 2 s .c  o  m
public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) {
    if (!Bundle.class.isAssignableFrom(type.getRawType())) {
        return null;
    }
    return (TypeAdapter<T>) new TypeAdapter<Bundle>() {
        @Override
        public void write(JsonWriter out, Bundle bundle) throws IOException {
            if (bundle == null) {
                out.nullValue();
                return;
            }
            out.beginObject();
            for (String key : bundle.keySet()) {
                out.name(key);
                Object value = bundle.get(key);
                if (value == null) {
                    out.nullValue();
                } else {
                    gson.toJson(value, value.getClass(), out);
                }
            }
            out.endObject();
        }

        @Override
        public Bundle read(JsonReader in) throws IOException {
            switch (in.peek()) {
            case NULL:
                in.nextNull();
                return null;
            case BEGIN_OBJECT:
                return toBundle(readObject(in));
            default:
                throw new IOException("expecting object: " + in.getPath());
            }
        }

        private Bundle toBundle(List<Pair<String, Object>> values) throws IOException {
            Bundle bundle = new Bundle();
            for (Pair<String, Object> entry : values) {
                String key = entry.first;
                Object value = entry.second;
                if (value instanceof String) {
                    bundle.putString(key, (String) value);
                } else if (value instanceof Integer) {
                    bundle.putInt(key, ((Integer) value).intValue());
                } else if (value instanceof Long) {
                    bundle.putLong(key, ((Long) value).longValue());
                } else if (value instanceof Double) {
                    bundle.putDouble(key, ((Double) value).doubleValue());
                } else if (value instanceof Parcelable) {
                    bundle.putParcelable(key, (Parcelable) value);
                } else if (value instanceof List) {
                    List<Pair<String, Object>> objectValues = (List<Pair<String, Object>>) value;
                    Bundle subBundle = toBundle(objectValues);
                    bundle.putParcelable(key, subBundle);
                } else {
                    throw new IOException("Unparcelable key, value: " + key + ", " + value);
                }
            }
            return bundle;
        }

        private List<Pair<String, Object>> readObject(JsonReader in) throws IOException {
            List<Pair<String, Object>> object = new ArrayList<Pair<String, Object>>();
            in.beginObject();
            while (in.peek() != JsonToken.END_OBJECT) {
                switch (in.peek()) {
                case NAME:
                    String name = in.nextName();
                    Object value = readValue(in);
                    object.add(new Pair<String, Object>(name, value));
                    break;
                case END_OBJECT:
                    break;
                default:
                    throw new IOException("expecting object: " + in.getPath());
                }
            }
            in.endObject();
            return object;
        }

        private Object readValue(JsonReader in) throws IOException {
            switch (in.peek()) {
            case BEGIN_ARRAY:
                return readArray(in);
            case BEGIN_OBJECT:
                return readObject(in);
            case BOOLEAN:
                return in.nextBoolean();
            case NULL:
                in.nextNull();
                return null;
            case NUMBER:
                return readNumber(in);
            case STRING:
                return in.nextString();
            default:
                throw new IOException("expecting value: " + in.getPath());
            }
        }

        private Object readNumber(JsonReader in) throws IOException {
            double doubleValue = in.nextDouble();
            if (doubleValue - Math.ceil(doubleValue) == 0) {
                long longValue = (long) doubleValue;
                if (longValue >= Integer.MIN_VALUE && longValue <= Integer.MAX_VALUE) {
                    return (int) longValue;
                }
                return longValue;
            }
            return doubleValue;
        }

        @SuppressWarnings("rawtypes")
        private List readArray(JsonReader in) throws IOException {
            List list = new ArrayList();
            in.beginArray();
            while (in.peek() != JsonToken.END_ARRAY) {
                Object element = readValue(in);
                list.add(element);
            }
            in.endArray();
            return list;
        }
    };
}

From source file:RestrictSerializationToBaseClassFactory.java

License:Apache License

@Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
    Class incoming = type.getRawType();
    if (subClasses != null) {
        boolean matched = false;
        for (Class<? extends B> subClass : subClasses) {
            if (incoming == subClass) {
                matched = true;/*from  ww w .j av a  2  s .c  o m*/
                break;
            }
        }
        if (!matched)
            return null;
    } else { // restricting all sub-classes since none specified
        // don't match the baseClass since we want to use the default factory for it
        if (incoming == baseClass || !baseClass.isAssignableFrom(incoming))
            return null;
    }
    TypeAdapter<T> adapter = new TypeAdapter<T>() {
        @Override
        public T read(JsonReader reader) throws IOException {
            final TypeAdapter subAdapter = gson.getDelegateAdapter(RestrictSerializationToBaseClassFactory.this,
                    type);
            return (T) subAdapter.read(reader);
        }

        @Override
        public void write(JsonWriter writer, T value) throws IOException {
            final TypeAdapter<B> baseAdapter = gson.getAdapter(baseClass);
            baseAdapter.write(writer, (B) value);
        }
    };
    return adapter;
}

From source file:blog.ClassTypeAdapterFactory.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*from ww w . j  av  a 2 s . c om*/
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    if (!Class.class.isAssignableFrom(typeToken.getRawType())) {
        return null;
    }
    return (TypeAdapter<T>) new ClassTypeAdapter();
}

From source file:ca.ualberta.cs.team1travelexpenseapp.gsonUtils.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }/* www .j  av  a  2s.co  m*/

    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>();
    for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
        TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
        labelToDelegate.put(entry.getKey(), delegate);
        subtypeToDelegate.put(entry.getValue(), delegate);
    }

    return new TypeAdapter<R>() {
        @Override
        public R read(JsonReader in) throws IOException {
            JsonElement jsonElement = Streams.parse(in);
            JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName);
            if (labelJsonElement == null) {
                throw new JsonParseException("cannot deserialize " + baseType
                        + " because it does not define a field named " + typeFieldName);
            }
            String label = labelJsonElement.getAsString();
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);
            if (delegate == null) {
                throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label
                        + "; did you forget to register a subtype?");
            }
            return delegate.fromJsonTree(jsonElement);
        }

        @Override
        public void write(JsonWriter out, R value) throws IOException {
            Class<?> srcType = value.getClass();
            String label = subtypeToLabel.get(srcType);
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType);
            if (delegate == null) {
                throw new JsonParseException(
                        "cannot serialize " + srcType.getName() + "; did you forget to register a subtype?");
            }
            JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();
            if (jsonObject.has(typeFieldName)) {
                throw new JsonParseException("cannot serialize " + srcType.getName()
                        + " because it already defines a field named " + typeFieldName);
            }
            JsonObject clone = new JsonObject();
            clone.add(typeFieldName, new JsonPrimitive(label));
            for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
                clone.add(e.getKey(), e.getValue());
            }
            Streams.write(clone, out);
        }
    };
}

From source file:cc.kave.commons.utils.json.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }/*w ww .j  ava 2s . c  o m*/

    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>();
    for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
        TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
        labelToDelegate.put(entry.getKey(), delegate);
        subtypeToDelegate.put(entry.getValue(), delegate);
    }

    return new TypeAdapter<R>() {
        @Override
        public R read(JsonReader in) throws IOException {
            JsonElement jsonElement = Streams.parse(in);
            // (kave adaptation) was: ".remove(typeFiledName)"
            JsonElement labelJsonElement = jsonElement.getAsJsonObject().get(typeFieldName);
            if (labelJsonElement == null) {
                throw new JsonParseException("cannot deserialize " + baseType
                        + " because it does not define a field named " + typeFieldName);
            }
            String label = labelJsonElement.getAsString();
            @SuppressWarnings("unchecked") // registration requires that
            // subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);
            if (delegate == null) {
                throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label
                        + "; did you forget to register a subtype?");
            }
            return delegate.fromJsonTree(jsonElement);
        }

        @Override
        public void write(JsonWriter out, R value) throws IOException {
            if (value == null) {
                Streams.write(null, out);
                return;
            }
            Class<?> srcType = value.getClass();
            String label = subtypeToLabel.get(srcType);
            @SuppressWarnings("unchecked") // registration requires that
            // subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType);
            if (delegate == null) {
                throw new JsonParseException(
                        "cannot serialize " + srcType.getName() + "; did you forget to register a subtype?");
            }
            JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();
            // (kave adaptation) disabled check
            // if (jsonObject.has(typeFieldName)) {
            // throw new JsonParseException("cannot serialize " +
            // srcType.getName()
            // + " because it already defines a field named " +
            // typeFieldName);
            // }
            JsonObject clone = new JsonObject();
            clone.add(typeFieldName, new JsonPrimitive(label));
            for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
                clone.add(e.getKey(), e.getValue());
            }
            Streams.write(clone, out);
        }
    };
}

From source file:ch.uzh.ifi.seal.soprafs15.group_00_android.models.gson.AutoValueAdapterFactory.java

License:Apache License

@SuppressWarnings("unchecked")

@Override//  w ww  .  j av a 2  s.co  m
public <T> TypeAdapter<T> create(Gson gson, 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 + ".AutoParcel_" + className;

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

From source file:cmput301w15t07.TravelTracker.util.DeletionFlagTypeAdapterFactory.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*from w  w  w  .  ja v a  2 s .  com*/
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    // TODO technically isAssignableFrom is deprecated and we should change
    // it. Maybe some time in the future.
    if (!DeletionFlag.class.isAssignableFrom(type.getRawType())) {
        return null;
    }

    Log.d("TypeAdapter", "Good type: " + type.getRawType().getCanonicalName());
    for (Type param : ((ParameterizedType) type.getType()).getActualTypeArguments()) {
        Log.d("TypeAdapter", "Parameter type: " + param.toString());
    }

    // Get the parameterizing type
    Type elementType = ((ParameterizedType) type.getType()).getActualTypeArguments()[0];

    // Get adapters specific to the object we need so that we can delegate
    TypeAdapter<?> documentAdapter = gson.getAdapter(TypeToken.get(elementType));

    return (TypeAdapter<T>) new DeletionFlagAdapter<Document>((TypeAdapter<Document>) documentAdapter);
}

From source file:cn.ieclipse.af.demo.sample.volley.adapter.CollectionsAdapter.java

License:Apache License

@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    Type type = typeToken.getType();

    Class<? super T> rawType = typeToken.getRawType();
    if (!Collection.class.isAssignableFrom(rawType)) {
        return null;
    }// w w w . j a  v  a2  s .c  o m

    Type elementType = $Gson$Types.getCollectionElementType(type, rawType);
    TypeAdapter<?> elementTypeAdapter = gson.getAdapter(TypeToken.get(elementType));
    ObjectConstructor<T> constructor = constructorConstructor.get(typeToken);

    @SuppressWarnings({ "unchecked", "rawtypes" }) // create() doesn't define a type parameter
    TypeAdapter<T> result = new Adapter(gson, elementType, elementTypeAdapter, constructor);
    return result;
}

From source file:cn.taop.utils.GSONUtils.java

License:Apache License

/**
 *  {@code JSON} ??/*  w  ww .  j  av a2s  .  c  om*/
 * 
 * @param <T> ??
 * @param json  {@code JSON} 
 * @param token {@code com.google.gson.reflect.TypeToken} 
 * @param datePattern ??
 * @return  {@code JSON} 
 * @since 1.0
 */
public static <T> T fromJson(String json, TypeToken<T> token, String datePattern) {
    if (StringUtils.isBlank(json)) {
        return null;
    }
    GsonBuilder builder = new GsonBuilder();
    if (StringUtils.isBlank(datePattern)) {
        datePattern = DEFAULT_DATE_PATTERN;
    }
    Gson gson = builder.create();
    try {
        return gson.fromJson(json, token.getType());
    } catch (Exception ex) {
        LOGGER.error(json + " ? " + token.getRawType().getName() + " !", ex);
        return null;
    }
}

From source file:co.cask.cdap.common.io.CaseInsensitiveEnumTypeAdapterFactory.java

License:Apache License

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

    final Map<String, T> lowercaseToConstant = new HashMap<>();
    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 {
                return lowercaseToConstant.get(toLowercase(reader.nextString()));
            }
        }
    };
}