Java Code Examples for com.google.gson.reflect.TypeToken#get()

The following examples show how to use com.google.gson.reflect.TypeToken#get() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GsonBuilder.java    From framework with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Configures Gson for custom serialization or deserialization. This method combines the
 * registration of an {@link TypeAdapter}, {@link InstanceCreator}, {@link JsonSerializer}, and a
 * {@link JsonDeserializer}. It is best used when a single object {@code typeAdapter} implements
 * all the required interfaces for custom serialization with Gson. If a type adapter was
 * previously registered for the specified {@code type}, it is overwritten.
 *
 * <p>This registers the type specified and no other types: you must manually register related
 * types! For example, applications registering {@code boolean.class} should also register {@code
 * Boolean.class}.
 *
 * @param type the type definition for the type adapter being registered
 * @param typeAdapter This object must implement at least one of the {@link TypeAdapter},
 * {@link InstanceCreator}, {@link JsonSerializer}, and a {@link JsonDeserializer} interfaces.
 * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
 */
@SuppressWarnings({"unchecked", "rawtypes"})
public GsonBuilder registerTypeAdapter(Type type, Object typeAdapter) {
  $Gson$Preconditions.checkArgument(typeAdapter instanceof JsonSerializer<?>
      || typeAdapter instanceof JsonDeserializer<?>
      || typeAdapter instanceof InstanceCreator<?>
      || typeAdapter instanceof TypeAdapter<?>);
  if (typeAdapter instanceof InstanceCreator<?>) {
    instanceCreators.put(type, (InstanceCreator) typeAdapter);
  }
  if (typeAdapter instanceof JsonSerializer<?> || typeAdapter instanceof JsonDeserializer<?>) {
    TypeToken<?> typeToken = TypeToken.get(type);
    factories.add(TreeTypeAdapter.newFactoryWithMatchRawType(typeToken, typeAdapter));
  }
  if (typeAdapter instanceof TypeAdapter<?>) {
    factories.add(TypeAdapters.newFactory(TypeToken.get(type), (TypeAdapter)typeAdapter));
  }
  return this;
}
 
Example 2
Source File: GsonInterfaceAdapter.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
private <S> S readValue(JsonObject jsonObject, TypeToken<S> defaultTypeToken) throws IOException {
  try {
    TypeToken<S> actualTypeToken;
    if (jsonObject.isJsonNull()) {
      return null;
    } else if (jsonObject.has(OBJECT_TYPE)) {
      String className = jsonObject.get(OBJECT_TYPE).getAsString();
      Class<S> klazz = (Class<S>) Class.forName(className);
      actualTypeToken = TypeToken.get(klazz);
    } else if (defaultTypeToken != null) {
      actualTypeToken = defaultTypeToken;
    } else {
      throw new IOException("Could not determine TypeToken.");
    }
    TypeAdapter<S> delegate = this.gson.getDelegateAdapter(this.factory, actualTypeToken);
    S value = delegate.fromJsonTree(jsonObject.get(OBJECT_DATA));
    return value;
  } catch (ClassNotFoundException cnfe) {
    throw new IOException(cnfe);
  }
}
 
Example 3
Source File: GsonBuilder.java    From gson with Apache License 2.0 6 votes vote down vote up
/**
 * Configures Gson for custom serialization or deserialization. This method combines the
 * registration of an {@link TypeAdapter}, {@link InstanceCreator}, {@link JsonSerializer}, and a
 * {@link JsonDeserializer}. It is best used when a single object {@code typeAdapter} implements
 * all the required interfaces for custom serialization with Gson. If a type adapter was
 * previously registered for the specified {@code type}, it is overwritten.
 *
 * <p>This registers the type specified and no other types: you must manually register related
 * types! For example, applications registering {@code boolean.class} should also register {@code
 * Boolean.class}.
 *
 * @param type the type definition for the type adapter being registered
 * @param typeAdapter This object must implement at least one of the {@link TypeAdapter},
 * {@link InstanceCreator}, {@link JsonSerializer}, and a {@link JsonDeserializer} interfaces.
 * @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
 */
@SuppressWarnings({"unchecked", "rawtypes"})
public GsonBuilder registerTypeAdapter(Type type, Object typeAdapter) {
  $Gson$Preconditions.checkArgument(typeAdapter instanceof JsonSerializer<?>
      || typeAdapter instanceof JsonDeserializer<?>
      || typeAdapter instanceof InstanceCreator<?>
      || typeAdapter instanceof TypeAdapter<?>);
  if (typeAdapter instanceof InstanceCreator<?>) {
    instanceCreators.put(type, (InstanceCreator) typeAdapter);
  }
  if (typeAdapter instanceof JsonSerializer<?> || typeAdapter instanceof JsonDeserializer<?>) {
    TypeToken<?> typeToken = TypeToken.get(type);
    factories.add(TreeTypeAdapter.newFactoryWithMatchRawType(typeToken, typeAdapter));
  }
  if (typeAdapter instanceof TypeAdapter<?>) {
    factories.add(TypeAdapters.newFactory(TypeToken.get(type), (TypeAdapter)typeAdapter));
  }
  return this;
}
 
Example 4
Source File: TwillRuntimeSpecificationAdapter.java    From twill with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
@Nullable
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
  Class<?> rawType = type.getRawType();
  if (!Map.class.isAssignableFrom(rawType)) {
    return null;
  }
  Type[] typeArgs = ((ParameterizedType) type.getType()).getActualTypeArguments();
  TypeToken<?> keyType = TypeToken.get(typeArgs[0]);
  TypeToken<?> valueType = TypeToken.get(typeArgs[1]);
  if (keyType.getRawType() != String.class) {
    return null;
  }
  return (TypeAdapter<T>) mapAdapter(gson, valueType);
}
 
Example 5
Source File: PolymorphicTypeAdapter.java    From rockscript with Apache License 2.0 6 votes vote down vote up
/** creates a map that maps generic type argument names to type tokens */
private static Map<String, TypeToken> getActualTypeArguments(TypeToken<?> typeToken) {
  Class<?> rawClass = typeToken.getRawType();
  Type type = typeToken.getType();
  TypeVariable<? extends Class<?>>[] typeParameters = rawClass.getTypeParameters();
  if (typeParameters==null || !(type instanceof ParameterizedType)) {
    return null;
  }
  Map<String, TypeToken> genericTypes = new HashMap<>();
  ParameterizedType parameterizedType = (ParameterizedType) type;
  Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
  for (int i=0; i<typeParameters.length; i++) {
    String typeParameterName = typeParameters[i].getName();
    TypeToken<?> actualType = TypeToken.get(actualTypeArguments[i]);
    genericTypes.put(typeParameterName, actualType);
  }
  return genericTypes;
}
 
Example 6
Source File: PolymorphicTypeAdapterFactory.java    From rockscript with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
  // TODO check if GSON does caching of the created TypeAdapter for the given type

  // extra caching could be added in this layer if there is only one polymorphic type
  // adapter for the whole hierarchy

  // https://google.github.io/gson/apidocs/com/google/gson/TypeAdapterFactory.html
  // If a factory cannot support a given type, it must return null when that type is passed to create(com.google.gson.Gson, com.google.gson.reflect.TypeToken<T>)

  if (type.getType() instanceof WildcardType) {
    WildcardType wildcardType = (WildcardType) type.getType();
    Type[] upperBounds = wildcardType.getUpperBounds();
    if (upperBounds!=null && upperBounds.length==1) {
      type = (TypeToken<T>) TypeToken.get(upperBounds[0]);
    } else {
      throw new RuntimeException("Unsupported wildcard type: "+type);
    }
  }
  if (matchingTypes.contains(type)) {
    if (typeAdapter==null) {
      typeAdapter = new PolymorphicTypeAdapter<T>(type, this, gson);
    }
    return (TypeAdapter<T>) this.typeAdapter;
  }

  return null;
}
 
Example 7
Source File: Jobs.java    From salt-netapi-client with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <R> RunnerCall<Map<String, Data<R>>> lookupJid(RunnerAsyncResult<R> jid) {
    LinkedHashMap<String, Object> args = new LinkedHashMap<>();
    args.put("jid", jid.getJid());
    Type dataType = parameterizedType(null, Data.class, jid.getType().getType());
    Type type = parameterizedType(null, Map.class, String.class, dataType);
    return new RunnerCall<>("jobs.lookup_jid", Optional.of(args),
            (TypeToken<Map<String, Data<R>>>) TypeToken.get(type));
}
 
Example 8
Source File: PolymorphicTypeAdapterFactory.java    From rockscript with Apache License 2.0 5 votes vote down vote up
public PolymorphicTypeAdapterFactory typeName(TypeToken<?> type, String name) {
  typeNames.put(type, name);

  matchingTypes.add(type);
  Class<?> rawClass = type.getRawType();
  TypeToken<?> rawType = TypeToken.get(rawClass);
  if (!rawType.equals(type)) {
    matchingTypes.add(rawType);
  }

  return this;
}
 
Example 9
Source File: Jobs.java    From salt-netapi-client with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <R> RunnerCall<Map<String, R>> lookupJid(LocalAsyncResult<R> jid) {
    LinkedHashMap<String, Object> args = new LinkedHashMap<>();
    args.put("jid", jid.getJid());
    Type type = parameterizedType(null, Map.class, String.class,
            jid.getType().getType());
    return new RunnerCall<>("jobs.lookup_jid", Optional.of(args),
            (TypeToken<Map<String, R>>) TypeToken.get(type));
}
 
Example 10
Source File: CustomGsonConverterFactory.java    From JianshuApp with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type,
                                                        Annotation[] annotations,
                                                        Retrofit retrofit) {
    TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
    return new GsonResponseBodyConverter<>(gson, adapter, TypeToken.get(type));
}
 
Example 11
Source File: Jobs.java    From salt-netapi-client with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <R> RunnerCall<Map<String, Data<R>>> lookupJid(WheelAsyncResult<R> jid) {
    LinkedHashMap<String, Object> args = new LinkedHashMap<>();
    args.put("jid", jid.getJid());
    Type dataType = parameterizedType(null, Data.class, jid.getType().getType());
    Type type = parameterizedType(null, Map.class, String.class, dataType);
    return new RunnerCall<>("jobs.lookup_jid", Optional.of(args),
            (TypeToken<Map<String, Data<R>>>) TypeToken.get(type));
}
 
Example 12
Source File: LaReflectiveTypeAdapterFactory.java    From lastaflute with Apache License 2.0 5 votes vote down vote up
protected Map<String, LaBoundField> getBoundFields(Gson context, TypeToken<?> type, Class<?> raw) {
    final Map<String, LaBoundField> result = new LinkedHashMap<String, LaBoundField>();
    if (raw.isInterface()) {
        return result;
    }
    final Type declaredType = type.getType();
    while (raw != Object.class) {
        final Field[] fields = raw.getDeclaredFields();
        for (Field field : fields) {
            boolean serialize = excludeField(field, true);
            final boolean deserialize = excludeField(field, false);
            if (!serialize && !deserialize) {
                continue;
            }
            field.setAccessible(true);
            final Type fieldType = $Gson$Types.resolve(type.getType(), raw, field.getGenericType());
            final List<String> fieldNames = getFieldNames(field);
            LaBoundField previous = null;
            for (int i = 0; i < fieldNames.size(); ++i) {
                final String name = fieldNames.get(i);
                if (i != 0)
                    serialize = false; // only serialize the default name
                final LaBoundField boundField =
                        createBoundField(context, field, name, TypeToken.get(fieldType), serialize, deserialize);
                final LaBoundField replaced = result.put(name, boundField);
                if (previous == null)
                    previous = replaced;
            }
            if (previous != null) {
                throw new IllegalArgumentException(declaredType + " declares multiple JSON fields named " + previous.name);
            }
        }
        type = TypeToken.get($Gson$Types.resolve(type.getType(), raw, raw.getGenericSuperclass()));
        raw = type.getRawType();
    }
    return result;
}
 
Example 13
Source File: LocalCall.java    From salt-netapi-client with MIT License 5 votes vote down vote up
/**
 * Helper to call an execution module function on the given target for batched or
 * unbatched while also providing an option to use the given credentials or to use a
 * prior created token. Synchronously waits for the result.
 *
 * @param client SaltClient instance
 * @param target the target for the function
 * @param batch the batch parameter, empty for unbatched
 * @param auth authentication credentials to use
 * @return A list of maps with each list representing each batch, and maps containing
 * the results with the minion names as keys. The first list is the entire
 * output for unbatched input.
 */
private CompletionStage<List<Map<String, Result<R>>>> callSyncHelperNonBlock(
        final SaltClient client, Target<?> target, AuthMethod auth, Optional<Batch> batch) {
    Map<String, Object> customArgs = new HashMap<>();
    batch.ifPresent(v -> customArgs.putAll(v.getParams()));

    Client clientType = batch.isPresent() ? Client.LOCAL_BATCH : Client.LOCAL;

    Type xor = parameterizedType(null, Result.class, getReturnType().getType());
    Type map = parameterizedType(null, Map.class, String.class, xor);
    Type listType = parameterizedType(null, List.class, map);
    Type wrapperType = parameterizedType(null, Return.class, listType);
    TypeToken<Return<List<Map<String, Result<R>>>>> typeToken =
            (TypeToken<Return<List<Map<String, Result<R>>>>>) TypeToken.get(wrapperType);

    if (batch.isPresent()) {
        return client.call(this,
                clientType,
                Optional.of(target),
                customArgs,
                typeToken,
                auth)
                .thenApply(Return::getResult)
                .thenApply(results -> handleRetcodeBatchingHack(results, xor));
    } else {
        return client.call(this,
                clientType,
                Optional.of(target),
                customArgs,
                typeToken,
                auth)
                .thenApply(Return::getResult);
    }
}
 
Example 14
Source File: PolymorphicTypeFields.java    From rockscript with Apache License 2.0 5 votes vote down vote up
/** adds all declared fields in the given inheritanceType to the polymorphicFields member field */
private void scanFields(TypeToken inheritanceType, Map<String, Type> actualTypeArguments, Gson gson) {
  Class rawClass = inheritanceType.getRawType();
  for (Field field: rawClass.getDeclaredFields()) {
    if (!Modifier.isTransient(field.getModifiers())) {
      Type fieldType = field.getGenericType();
      Type concreteFieldType = concretize(fieldType, actualTypeArguments);
      TypeToken<?> concreteFieldTypeToken = TypeToken.get(concreteFieldType);
      TypeAdapter<?> fieldTypeAdapter = gson.getAdapter(concreteFieldTypeToken);
      @SuppressWarnings("unchecked")
      PolymorphicField polymorphicField = new PolymorphicField(field, fieldTypeAdapter);
      polymorphicFields.put(field.getName(), polymorphicField);
    }
  }
}
 
Example 15
Source File: ReflectiveTypeAdapterFactory.java    From gson with Apache License 2.0 5 votes vote down vote up
private Map<String, BoundField> getBoundFields(Gson context, TypeToken<?> type, Class<?> raw) {
  Map<String, BoundField> result = new LinkedHashMap<String, BoundField>();
  if (raw.isInterface()) {
    return result;
  }

  Type declaredType = type.getType();
  while (raw != Object.class) {
    Field[] fields = raw.getDeclaredFields();
    for (Field field : fields) {
      boolean serialize = excludeField(field, true);
      boolean deserialize = excludeField(field, false);
      if (!serialize && !deserialize) {
        continue;
      }
      accessor.makeAccessible(field);
      Type fieldType = $Gson$Types.resolve(type.getType(), raw, field.getGenericType());
      List<String> fieldNames = getFieldNames(field);
      BoundField previous = null;
      for (int i = 0, size = fieldNames.size(); i < size; ++i) {
        String name = fieldNames.get(i);
        if (i != 0) serialize = false; // only serialize the default name
        BoundField boundField = createBoundField(context, field, name,
            TypeToken.get(fieldType), serialize, deserialize);
        BoundField replaced = result.put(name, boundField);
        if (previous == null) previous = replaced;
      }
      if (previous != null) {
        throw new IllegalArgumentException(declaredType
            + " declares multiple JSON fields named " + previous.name);
      }
    }
    type = TypeToken.get($Gson$Types.resolve(type.getType(), raw, raw.getGenericSuperclass()));
    raw = type.getRawType();
  }
  return result;
}
 
Example 16
Source File: GsonMessageConverter.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
protected TypeToken<?> getTypeToken(Type type) {
    return TypeToken.get(type);
}
 
Example 17
Source File: NetworkManager.java    From IceNet with Apache License 2.0 4 votes vote down vote up
@Override
public NetworkManager fromString() {
    this.resultType = RESULT.STRING;
    this.targetType = TypeToken.get(String.class);
    return new NetworkManager(this);
}
 
Example 18
Source File: NetworkManager.java    From IceNet with Apache License 2.0 4 votes vote down vote up
@Override
public NetworkManager mappingInto(@NonNull Class classTarget) {
    this.targetType = TypeToken.get(classTarget);
    return new NetworkManager(this);
}
 
Example 19
Source File: GsonHttpMessageConverter.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Return the Gson {@link TypeToken} for the specified type.
 * <p>The default implementation returns {@code TypeToken.get(type)}, but
 * this can be overridden in subclasses to allow for custom generic
 * collection handling. For instance:
 * <pre class="code">
 * protected TypeToken<?> getTypeToken(Type type) {
 *   if (type instanceof Class && List.class.isAssignableFrom((Class<?>) type)) {
 *     return new TypeToken<ArrayList<MyBean>>() {};
 *   }
 *   else {
 *     return super.getTypeToken(type);
 *   }
 * }
 * </pre>
 * @param type the type for which to return the TypeToken
 * @return the type token
 */
protected TypeToken<?> getTypeToken(Type type) {
	return TypeToken.get(type);
}
 
Example 20
Source File: GsonHttpMessageConverter.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Return the Gson {@link TypeToken} for the specified type.
 * <p>The default implementation returns {@code TypeToken.get(type)}, but
 * this can be overridden in subclasses to allow for custom generic
 * collection handling. For instance:
 * <pre class="code">
 * protected TypeToken<?> getTypeToken(Type type) {
 *   if (type instanceof Class && List.class.isAssignableFrom((Class<?>) type)) {
 *     return new TypeToken<ArrayList<MyBean>>() {};
 *   }
 *   else {
 *     return super.getTypeToken(type);
 *   }
 * }
 * </pre>
 * @param type the type for which to return the TypeToken
 * @return the type token
 * @deprecated as of Spring Framework 4.3.8, in favor of signature-based resolution
 */
@Deprecated
protected TypeToken<?> getTypeToken(Type type) {
	return TypeToken.get(type);
}