List of usage examples for com.google.gson.reflect TypeToken get
public static <T> TypeToken<T> get(Class<T> type)
From source file:com.cliff.hsj.api.common.GsonConverterFactory.java
License:Apache License
/** * Create a converter for {@code type}.// w w w. jav a 2 s . co m */ @Override public Converter<?> get(Type type) { TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type)); return new GsonConverter<>(adapter); }
From source file:com.cloud.network.nicira.NiciraNvpApi.java
License:Apache License
protected <T> T executeCreateObject(T newObject, Type returnObjectType, String uri, Map<String, String> parameters) throws NiciraNvpApiException { if (_host == null || _host.isEmpty() || _adminuser == null || _adminuser.isEmpty() || _adminpass == null || _adminpass.isEmpty()) {/* ww w .ja v a 2s .com*/ throw new NiciraNvpApiException("Hostname/credentials are null or empty"); } Gson gson = new Gson(); PostMethod pm = (PostMethod) createMethod("post", uri); pm.setRequestHeader("Content-Type", "application/json"); try { pm.setRequestEntity(new StringRequestEntity(gson.toJson(newObject), "application/json", null)); } catch (UnsupportedEncodingException e) { throw new NiciraNvpApiException("Failed to encode json request body", e); } executeMethod(pm); if (pm.getStatusCode() != HttpStatus.SC_CREATED) { String errorMessage = responseToErrorMessage(pm); pm.releaseConnection(); s_logger.error("Failed to create object : " + errorMessage); throw new NiciraNvpApiException("Failed to create object : " + errorMessage); } T result; try { result = (T) gson.fromJson(pm.getResponseBodyAsString(), TypeToken.get(newObject.getClass()).getType()); } catch (IOException e) { throw new NiciraNvpApiException("Failed to decode json response body", e); } finally { pm.releaseConnection(); } return result; }
From source file:com.csy.net.net.converter.GsonConverterFactory.java
License:Apache License
@Override public Converter<ResponseBody, ?> responseBodyConverter(final Type type, Annotation[] annotations, Retrofit retrofit) {//w ww . j a v a 2s . c om Type newType = new ParameterizedType() { @Override public Type[] getActualTypeArguments() { return new Type[] { type }; } @Override public Type getOwnerType() { return null; } @Override public Type getRawType() { return BasicResponse.class; } }; TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(newType)); return new GsonResponseBodyConverter<>(adapter); }
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 ww . ja v a2 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
private <T> TypeAdapter getDelegate(Gson gson, TypeToken<T> type) { Class<?> iface = type.getRawType(); if (!iface.isInterface()) iface = interfaceMap.get(iface); checkState(iface != null, "Non-mappable type found"); return gson.getDelegateAdapter(this, TypeToken.get(iface)); }
From source file:com.datastore_android_sdk.serialization.ForeignCollectionTypeAdapterFactory.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 (!ForeignCollection.class.isAssignableFrom(rawType)) { return null; }/* w w w.j a v a2 s . c om*/ final Type elementType = $Gson$Types.getCollectionElementType(type, rawType); TypeToken<?> elementTypeToken = TypeToken.get(elementType); // Specify a TypeAdapter for the element only if we can retreive a concrete type element type TypeAdapter<?> elementTypeAdapter = elementType instanceof TypeVariable ? null : gson.getAdapter(elementTypeToken); @SuppressWarnings({ "unchecked", "rawtypes" }) TypeAdapter<T> result = (TypeAdapter<T>) new Adapter(gson, elementType, elementTypeAdapter) { @Override public ObjectConstructor<T> getConstructor(final ForeignCollectionDeserializationContext context) { return new ObjectConstructor<T>() { public T construct() { if (creator == null) { return null; } else { return (T) creator.createInstance(elementType, context.getParent(), context.getColumnName(), context.getOrderColumnName(), context.getOrderAscending()); } } }; } }; return result; }
From source file:com.datastore_android_sdk.serialization.ModelTypeAdapterFactory.java
License:Apache License
/** * Searches the registered serialization strategies to find the best matching * strategy for the given {@code type}./*from w ww . j a v a 2 s .co m*/ * * @param type * The raw type of the object to find a serialization strategy * @return The best matching serialization strategy or {@code null} if * serialization strategy registered for the given {@code type} */ private ModelSerializationStrategy findSerializationStrategy(Class<?> type) { if (type != null) { Class<?> rawType = type; TypeToken<?> typeToken = TypeToken.get(rawType); // Find if there is a serialization strategy registered for the super // classes while (rawType != Object.class) { if (serializationStrategies.containsKey(rawType)) { return serializationStrategies.get(rawType); } typeToken = TypeToken .get($Gson$Types.resolve(typeToken.getType(), rawType, rawType.getGenericSuperclass())); rawType = typeToken.getRawType(); } // Find if there is a serialization strategy registered for an interface // the type implement Type[] interfaces = type.getGenericInterfaces(); for (Type i : interfaces) { if (serializationStrategies.containsKey(i)) { return serializationStrategies.get(i); } } } return null; }
From source file:com.datastore_android_sdk.serialization.ModelTypeAdapterFactory.java
License:Apache License
/** * Creates the bound fields for the given type. * /*from ww w . j av a 2 s .co m*/ * @param context the Gson context * @param type the type of the class * @param raw the raw type of the class * @return a map of bound fields */ protected Map<String, ModelBoundField> getBoundFields(Gson context, TypeToken<?> type, Class<?> raw) { Map<String, ModelBoundField> result = new LinkedHashMap<String, ModelBoundField>(); if (raw.isInterface()) { return result; } Class<?> rawType = raw; TypeToken<?> typeToken = type; Type declaredType = typeToken.getType(); while (rawType != Object.class) { Field[] fields = rawType.getDeclaredFields(); for (Field field : fields) { boolean serialize = includeField(field, true); boolean deserialize = includeField(field, false); if (!serialize && !deserialize) { continue; } field.setAccessible(true); Type fieldType = $Gson$Types.resolve(typeToken.getType(), rawType, field.getGenericType()); ModelBoundField boundField = createBoundField(context, field, getFieldName(field), TypeToken.get(fieldType), serialize, deserialize); BoundField previous = result.put(boundField.name, boundField); if (previous != null) { throw new IllegalArgumentException( declaredType + " declared multiple JSON fields named " + previous.name); } } typeToken = TypeToken .get($Gson$Types.resolve(typeToken.getType(), rawType, rawType.getGenericSuperclass())); rawType = typeToken.getRawType(); } return result; }
From source file:com.datastore_android_sdk.serialization.TypeAdapterRuntimeTypeWrapper.java
License:Apache License
@SuppressWarnings("rawtypes") public TypeAdapter getRuntimeTypeAdapter(T value) { // Order of preference for choosing type adapters // First preference: a type adapter registered for the runtime type // Second preference: a type adapter registered for the declared type // Third preference: reflective type adapter for the runtime type (if it is a sub class of the declared type) // Fourth preference: reflective type adapter for the declared type TypeAdapter chosen = delegate;/*w ww. jav a 2s.co m*/ Type runtimeType = getRuntimeTypeIfMoreSpecific(type, value); if (runtimeType != type) { // NOPMD TypeAdapter runtimeTypeAdapter = context.getAdapter(TypeToken.get(runtimeType)); if (!(runtimeTypeAdapter instanceof ModelTypeAdapter)) { // The user registered a type adapter for the runtime type, so // we will use that chosen = runtimeTypeAdapter; } else if (delegate != null && !(delegate instanceof ModelTypeAdapter)) { // The user registered a type adapter for Base class, so we // prefer it over the // reflective type adapter for the runtime type chosen = delegate; } else { // Use the type adapter for runtime type chosen = runtimeTypeAdapter; } } return chosen; }
From source file:com.devicehive.json.adapters.RuntimeTypeAdapterFactory.java
License:Apache License
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) { if (type.getRawType() != baseType) { return null; }/*from www . 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 = jsonElement.getAsJsonObject().remove(typeFieldName); 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 { 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); Streams.write(jsonObject, out); } }.nullSafe(); }