List of usage examples for com.google.gson.reflect TypeToken getRawType
public final Class<? super T> getRawType()
From source file:org.smartparam.manager.json.vendor.gson.ParameterDiffSerializer.java
License:Apache License
@Override @SuppressWarnings("unchecked") public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) { if (ParameterDiff.class.isAssignableFrom(type.getRawType())) { return (TypeAdapter) new TypeAdapter<ParameterDiff>() { @Override// w ww . j av a 2 s . co m public void write(JsonWriter out, ParameterDiff value) throws IOException { out.beginObject().name("previous").value(gson.toJson(value.previous())).name("current") .value(gson.toJson(value.current())).endObject(); } @Override public ParameterDiff read(JsonReader in) throws IOException { in.beginObject(); in.nextName(); SimpleParameter previous = gson.fromJson(in, SimpleParameter.class); in.nextName(); SimpleParameter current = gson.fromJson(in, SimpleParameter.class); in.endObject(); return new ParameterDiff(previous, current); } }; } return null; }
From source file:org.smartparam.manager.json.vendor.gson.ParameterEntryDiffSerializer.java
License:Apache License
@Override @SuppressWarnings("unchecked") public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) { if (ParameterEntryDiff.class.isAssignableFrom(type.getRawType())) { return (TypeAdapter) new TypeAdapter<ParameterEntryDiff>() { @Override/*from w w w .j a v a 2 s . co m*/ public void write(JsonWriter out, ParameterEntryDiff value) throws IOException { out.beginObject().name("previous").value(gson.toJson(value.previous())).name("current") .value(gson.toJson(value.current())).endObject(); } @Override public ParameterEntryDiff read(JsonReader in) throws IOException { in.beginObject(); in.nextName(); SimpleParameterEntry previous = gson.fromJson(in, SimpleParameterEntry.class); in.nextName(); SimpleParameterEntry current = gson.fromJson(in, SimpleParameterEntry.class); in.endObject(); return new ParameterEntryDiff(previous, current); } }; } return null; }
From source file:org.smartparam.manager.json.vendor.gson.ParameterEntryKeySerializer.java
License:Apache License
@Override @SuppressWarnings("unchecked") public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { if (ParameterEntryKey.class.isAssignableFrom(type.getRawType())) { return (TypeAdapter) new TypeAdapter<ParameterEntryKey>() { @Override//from w ww .j a v a 2 s. co m public void write(JsonWriter out, ParameterEntryKey value) throws IOException { out.value(value.value()); } @Override public ParameterEntryKey read(JsonReader in) throws IOException { return new SimpleParameterEntryKey(in.nextString()); } }; } return null; }
From source file:org.sprintapi.hyperdata.gson.HyperDataAdapterFactory.java
License:Apache License
@SuppressWarnings("unchecked") @Override// w w w .java 2s .c o m public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { Class<? super T> raw = type.getRawType(); if (!Object.class.isAssignableFrom(raw) || HyperMap.class.isAssignableFrom(raw)) { return null; // it's a primitive or HyperMap } if (!raw.isAnnotationPresent(HyperdataContainer.class)) { return null; // it's not hyperdata } MetadataAccess metadataAccess = new MetadataAccess(); Set<String> profiles = new LinkedHashSet<String>(); Class<?> c = raw; while (c != null) { if (c.getClass().equals(Object.class)) { break; } HyperdataContainer hdc = c.getAnnotation(HyperdataContainer.class); if ((hdc != null) && (hdc.profile().length > 0)) { profiles.addAll(Arrays.asList(hdc.profile())); } Class<?>[] interfaces = c.getInterfaces(); if (interfaces != null) { for (Class<?> i : interfaces) { hdc = i.getAnnotation(HyperdataContainer.class); if ((hdc != null) && (hdc.profile().length > 0)) { profiles.addAll(Arrays.asList(hdc.profile())); } } } c = c.getSuperclass(); } metadataAccess.profile = profiles.toArray(new String[0]); for (Method method : raw.getMethods()) { if (method.isAnnotationPresent(MetadataContainer.class)) { if (method.getName().startsWith("get")) { metadataAccess.getter = method; metadataAccess.fieldName = method.getName().substring(3); } else if (method.getName().startsWith("set")) { metadataAccess.setter = method; metadataAccess.fieldName = method.getName().substring(3); } } } if (metadataAccess.fieldName != null) { if (metadataAccess.getter == null) { for (Method method : raw.getMethods()) { if (method.getName().equals("get" + metadataAccess.fieldName)) { metadataAccess.getter = method; break; } } } else if (metadataAccess.setter == null) { for (Method method : raw.getMethods()) { if (method.getName().equals("set" + metadataAccess.fieldName)) { metadataAccess.setter = method; break; } } } metadataAccess.fieldName = WordUtils.uncapitalize(metadataAccess.fieldName); } ObjectConstructor<T> constructor = constructorConstructor.get(type); return (TypeAdapter<T>) new HyperDataTypeAdapter(metadataAccess, constructorConstructor, (ObjectConstructor<Object>) constructor, getBoundFields(gson, type, raw), gson, this); }
From source file:org.syphr.lametrictime.api.common.impl.typeadapters.imported.RuntimeTypeAdapterFactory.java
License:Apache License
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) { if (type.getRawType() != baseType) { return null; }// w ww . jav a 2 s . 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 = RuntimeTypeAdapterFactory.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()); } RuntimeTypeAdapterFactory.write(clone, out); } }.nullSafe(); }
From source file:org.terasology.persistence.typeHandling.gson.GsonTypeHandlerAdapterFactory.java
License:Apache License
@SuppressWarnings("unchecked") @Override//from ww w . j ava2s . c o m public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { Class<? super T> rawType = type.getRawType(); if (!containsTypeHandlerFor(rawType)) { return null; } return new GsonTypeHandlerAdapter<>((TypeHandler<T>) typeHandlerMap.get(rawType), gson, type); }
From source file:org.terasology.persistence.typeHandling.gson.PolymorphicTypeAdapterFactory.java
License:Apache License
@Override public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) { if (!baseClass.isAssignableFrom(type.getRawType())) { return null; }/*from w ww .j a va2s . co m*/ return new TypeAdapter<R>() { @SuppressWarnings("unchecked") @Override public void write(JsonWriter out, R value) throws IOException { Class<?> valueClass = value.getClass(); String valueTypeName = valueClass.getName(); TypeToken<?> valueType = TypeToken.get(valueClass); TypeAdapter<R> delegate = (TypeAdapter<R>) gson .getDelegateAdapter(PolymorphicTypeAdapterFactory.this, valueType); if (delegate == null) { throw new JsonParseException("Could not serialize " + valueClass.getName()); } JsonElement jsonElement = delegate.toJsonTree(value); if (valueClass != baseClass) { JsonObject jsonObject = jsonElement.getAsJsonObject(); JsonObject clone = new JsonObject(); clone.add(TYPE_FIELD_NAME, new JsonPrimitive(valueTypeName)); for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) { clone.add(e.getKey(), e.getValue()); } Streams.write(clone, out); } else { Streams.write(jsonElement, out); } } @SuppressWarnings("unchecked") @Override public R read(JsonReader in) throws IOException { JsonElement jsonElement = Streams.parse(in); Class<?> valueClass; if (jsonElement.isJsonObject()) { JsonElement typeNameJsonElement = jsonElement.getAsJsonObject().remove(TYPE_FIELD_NAME); if (typeNameJsonElement != null) { String typeName = typeNameJsonElement.getAsString(); try { valueClass = Class.forName(typeName); } catch (ClassNotFoundException e) { throw new JsonParseException("Could not find class " + typeName); } } else { valueClass = baseClass; } } else { valueClass = baseClass; } if (!baseClass.isAssignableFrom(valueClass)) { throw new JsonParseException( valueClass.getName() + " does not derive from " + baseClass.getName()); } TypeToken<?> valueType = TypeToken.get(valueClass); TypeAdapter<R> delegate = (TypeAdapter<R>) gson .getDelegateAdapter(PolymorphicTypeAdapterFactory.this, valueType); if (delegate == null) { throw new JsonParseException("Could not deserialize " + valueClass.getName()); } return delegate.fromJsonTree(jsonElement); } }; }
From source file:org.terasology.utilities.gson.CaseInsensitiveEnumTypeAdapterFactory.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 .java 2 s . c o m final Map<String, T> lowercaseToConstant = Maps.newHashMap(); for (T constant : rawType.getEnumConstants()) { String lowercase = toLowercase(constant); lowercaseToConstant.put(lowercase, constant); } return new TypeAdapter<T>() { @Override public void write(JsonWriter out, T value) throws IOException { if (value == null) { out.nullValue(); } else { out.value(toLowercase(value)); } } @Override public T read(JsonReader reader) throws IOException { if (reader.peek() == JsonToken.NULL) { reader.nextNull(); return null; } else { String value = reader.nextString(); return lowercaseToConstant.get(toLowercase(value)); } } }; }
From source file:org.terasology.utilities.gson.UriTypeAdapterFactory.java
License:Apache License
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { final Class<T> rawType = (Class<T>) type.getRawType(); if (!Uri.class.isAssignableFrom(rawType)) { return null; }/*www.jav a 2 s .c om*/ final Constructor<T> constructor; try { constructor = rawType.getConstructor(String.class); constructor.setAccessible(true); } catch (NoSuchMethodException e) { logger.error("URI type {} lacks String constructor", rawType); return null; } return new TypeAdapter<T>() { @Override public void write(JsonWriter out, T value) throws IOException { out.value(value.toString()); } @Override public T read(JsonReader reader) throws IOException { if (reader.peek() == JsonToken.NULL) { reader.nextNull(); return null; } else { String nextString = reader.nextString(); try { return constructor.newInstance(nextString); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { logger.error("Failed to instantiate uri of type {} from value {}", rawType, nextString, e); return null; } } } }; }
From source file:org.wso2.msf4j.internal.router.ParamConvertUtils.java
License:Open Source License
/** * Common helper method to convert value for {@link javax.ws.rs.HeaderParam} and {@link javax.ws.rs.QueryParam}. * * @param resultType Result type// w ww. ja v a2s . co m * @return Function the function * @see #createHeaderParamConverter(Type) * @see #createQueryParamConverter(Type) */ private static Function<List<String>, Object> createListConverter(Type resultType) { TypeToken<?> typeToken = TypeToken.get(resultType); // Use boxed type if raw type is primitive type. Otherwise the type won't change. Class<?> resultClass = typeToken.getRawType(); // For string, just return the first value if (resultClass == String.class) { return new BasicConverter(Defaults.defaultValue(resultClass)) { @Override protected Object convert(String value) throws Exception { return value; } }; } // Creates converter based on the type // Primitive Function<List<String>, Object> converter = createPrimitiveTypeConverter(resultClass); if (converter != null) { return converter; } // String constructor converter = createStringConstructorConverter(resultClass); if (converter != null) { return converter; } // Static string argument methods converter = createStringMethodConverter(resultClass); if (converter != null) { return converter; } // Collection converter = createCollectionConverter(typeToken); if (converter != null) { return converter; } throw new IllegalArgumentException("Unsupported type " + typeToken); }