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:de.lulebe.designer.external.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type == null || !baseType.isAssignableFrom(type.getRawType())) {
        return null;
    }/*from w w  w .jav a 2  s  .  c om*/

    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);
        }
    }.nullSafe();
}

From source file:de.micromata.genome.junittools.wicket.models.WicketTestBuilderGsonBuilder.java

License:Apache License

public static Gson getGson() {
    if (gsonBuilder == null) {
        gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapterFactory(new TypeAdapterFactory() {

            @Override//from w ww. j a v  a 2  s. c  o m
            public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
                if (type.getRawType() == Class.class) {
                    return new TypeAdapter<T>() {
                        @Override
                        public void write(JsonWriter out, T value) throws IOException {
                            out.value(((Class) value).getName());
                        }

                        @Override
                        public T read(JsonReader in) throws IOException {
                            try {
                                return (T) Class.forName(in.nextString());
                            } catch (ClassNotFoundException e) {
                                LOG.error("unable to transform " + in.nextString()
                                        + " to a reasonable class, please check this!");
                            }
                            return null;
                        }
                    };
                }
                return null;
            }
        });
    }
    return gsonBuilder.create();
}

From source file:de.symeda.sormas.app.rest.RuntimeTypeAdapterFactory.java

License:Open Source License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }//from   w ww .j a  v  a2s.  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);
            JsonElement labelJsonElement;
            if (maintainType) {
                labelJsonElement = jsonElement.getAsJsonObject().get(typeFieldName);
            } else {
                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 (maintainType) {
                Streams.write(jsonObject, out);
                return;
            }

            JsonObject clone = new JsonObject();

            if (jsonObject.has(typeFieldName)) {
                throw new JsonParseException("cannot serialize " + srcType.getName()
                        + " because it already defines a field named " + typeFieldName);
            }
            clone.add(typeFieldName, new JsonPrimitive(label));

            for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
                clone.add(e.getKey(), e.getValue());
            }
            Streams.write(clone, out);
        }
    }.nullSafe();
}

From source file:edu.mit.media.funf.config.DefaultRuntimeTypeAdapterFactory.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*  w ww  . j a va 2  s.  com*/
public <T> Class<? extends T> getRuntimeType(JsonElement el, TypeToken<T> type) {
    if (baseClass.isAssignableFrom(type.getRawType())) {
        // 1 use type if instatiable
        // 2 use default if type cannot be instantiated and type is assignable from type
        // 3 fail
        final boolean canUseDefaultClass = defaultClass != null
                && type.getRawType().isAssignableFrom(defaultClass);
        final boolean typeIsInstantiable = DefaultRuntimeTypeAdapterFactory
                .isTypeInstatiable(type.getRawType());
        final Class<? extends T> defautRuntimeClass = (Class<? extends T>) (typeIsInstantiable
                ? type.getRawType()
                : (canUseDefaultClass ? defaultClass : null));
        return DefaultRuntimeTypeAdapterFactory.getRuntimeType(el, (Class<T>) type.getRawType(),
                defautRuntimeClass);
    }
    return null;
}

From source file:edu.mit.media.funf.config.DefaultRuntimeTypeAdapterFactory.java

License:Open Source License

@Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
    if (baseClass.isAssignableFrom(type.getRawType())) {
        return new TypeAdapter<T>() {
            @Override/*  w  ww  .ja  v  a  2  s.  c  om*/
            public void write(JsonWriter out, T value) throws IOException {
                if (value == null) {
                    out.nullValue();
                    return;
                }
                // TODO: cache these only once per runtime type
                final TypeAdapter delegate = delegateFactory.create(gson, TypeToken.get(value.getClass()));
                JsonTreeWriter treeWriter = new JsonTreeWriter();
                delegate.write(treeWriter, value);
                JsonElement el = treeWriter.get();

                if (el.isJsonObject()) {
                    JsonObject elObject = el.getAsJsonObject();
                    elObject.addProperty(RuntimeTypeAdapterFactory.TYPE, value.getClass().getName());
                    Streams.write(elObject, out);
                } else {
                    Streams.write(el, out);
                }
            }

            @Override
            public T read(JsonReader in) throws IOException {
                // TODO: need to handle null
                JsonElement el = Streams.parse(in);
                Class<? extends T> runtimeType = getRuntimeType(el, type);
                if (runtimeType == null) {
                    throw new ParseException("RuntimeTypeAdapter: Unable to parse runtime type.");
                }
                // TODO: cache these only once per runtime type
                final TypeAdapter<? extends T> delegate = delegateFactory.create(gson,
                        TypeToken.get(runtimeType));

                if (el.isJsonPrimitive() && el.getAsJsonPrimitive().isString()) {
                    JsonObject typeObject = new JsonObject();
                    typeObject.addProperty(TYPE, el.getAsString());
                    el = typeObject;
                }

                return delegate.read(new JsonTreeReader(el));
            }

        };
    }
    return null;
}

From source file:gobblin.util.io.GsonInterfaceAdapter.java

License:Apache License

@Override
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (ClassUtils.isPrimitiveOrWrapper(type.getRawType()) || type.getType() instanceof GenericArrayType
            || CharSequence.class.isAssignableFrom(type.getRawType())
            || (type.getType() instanceof ParameterizedType
                    && (Collection.class.isAssignableFrom(type.getRawType())
                            || Map.class.isAssignableFrom(type.getRawType())))) {
        // delegate primitives, arrays, collections, and maps
        return null;
    }/*  w w  w .  j a  va2 s .c om*/
    if (!this.baseClass.isAssignableFrom(type.getRawType())) {
        // delegate anything not assignable from base class
        return null;
    }
    TypeAdapter<R> adapter = new InterfaceAdapter<>(gson, this, type);
    return adapter;
}

From source file:io.barracks.ota.client.UpdateCheckService.java

License:Apache License

/**
 * {@inheritDoc}/*from   ww w .ja  va 2 s  .  co  m*/
 */
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    if (type.getRawType() == Bundle.class) {
        return (TypeAdapter<T>) getBundleAdapter(gson);
    }
    return null;
}

From source file:io.github.rcarlosdasilva.weixin.core.json.CustomTypeAdapterFactory.java

@SuppressWarnings("unchecked")
@Override//w  w  w .jav a 2  s .  com
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    Class<? super T> clazz = type.getRawType();
    if (clazz == MessageSendWithMassRequestUser.class) {
        return (TypeAdapter<T>) new MessageSendWithMassRequestUserTypeAdapter().nullSafe();
    } else if (clazz == AccessTokenResponse.class) {
        return (TypeAdapter<T>) new AccessTokenResponseTypeAdapter().nullSafe();
    } else if (clazz == OpenPlatformAuthAccessTokenResponse.class) {
        return (TypeAdapter<T>) new OpenPlatformAuthAccessTokenResponseTypeAdapter().nullSafe();
    } else if (clazz == OpenPlatformAuthGetLicenseInformationResponse.class) {
        return (TypeAdapter<T>) new OpenPlatformAuthGetLicenseInformationResponseTypeAdapter().nullSafe();
    }
    return null;
}

From source file:io.hops.hopsworks.api.zeppelin.json.NotebookTypeAdapterFactory.java

License:Apache License

@SuppressWarnings("unchecked")
// we use a runtime check to guarantee that 'C' and 'T' are equal
public final <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    return type.getRawType() == customizedClass
            ? (TypeAdapter<T>) customizeTypeAdapter(gson, (TypeToken<C>) type)
            : null;/*from w ww.j  a  v a2s. c om*/
}

From source file:io.prediction.workflow.JavaQueryTypeAdapterFactory.java

License:Apache License

@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    if (type.getRawType().equals(JavaQuery.class)) {
        return (TypeAdapter<T>) new TypeAdapter<JavaQuery>() {
            public void write(JsonWriter out, JavaQuery value) throws IOException {
                if (value == null) {
                    out.nullValue();/*w  w w. ja  va  2s . c  om*/
                } else {
                    out.beginObject();
                    out.name("q").value(value.getQ().toUpperCase());
                    out.endObject();
                }
            }

            public JavaQuery read(JsonReader reader) throws IOException {
                if (reader.peek() == JsonToken.NULL) {
                    reader.nextNull();
                    return null;
                } else {
                    reader.beginObject();
                    reader.nextName();
                    String q = reader.nextString();
                    reader.endObject();
                    return new JavaQuery(q.toUpperCase());
                }
            }
        };
    } else {
        return null;
    }
}