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

The following examples show how to use com.google.gson.reflect.TypeToken#getType() . 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: PolymorphicTypeFields.java    From rockscript with Apache License 2.0 7 votes vote down vote up
/** creates a map that maps generic type argument names to type tokens */
private static Map<String, Type> 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, Type> genericTypes = new HashMap<>();
  ParameterizedType parameterizedType = (ParameterizedType) type;
  Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
  for (int i=0; i<typeParameters.length; i++) {
    String typeParameterName = typeParameters[i].getName();
    Type actualType = actualTypeArguments[i];
    genericTypes.put(typeParameterName, actualType);
  }
  return genericTypes;
}
 
Example 2
Source File: _GsonUtil.java    From proguard with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the appropriate type adapter for handling the given value with
 * the given declared type token.
 *
 * @param gson              the Gson context that manages all registered type
 *                          adapters.
 * @param declaredTypeToken the declared type token of the value to (de)serialize.
 * @param value             the value to (de)serialize.
 * @return                  the type adapter for handling the given value and
 *                          declared type.
 */
public static TypeAdapter getTypeAdapter(Gson gson, TypeToken declaredTypeToken, Object value)
{
    // If the runtime type is a sub type and there is a custom type adapter registered for
    // the declared type, that one should get precedence over the runtime type adapter if
    // the runtime type adapter is not custom.
    Type declaredType = declaredTypeToken.getType();
    Type runtimeType = getRuntimeTypeIfMoreSpecific(declaredType, value);
    TypeAdapter runtimeTypeAdapter = gson.getAdapter(TypeToken.get(runtimeType));
    if (declaredType != runtimeType && !isCustomTypeAdapter(runtimeTypeAdapter))
    {
        TypeAdapter declaredTypeAdapter = gson.getAdapter(declaredTypeToken);
        if (isCustomTypeAdapter(declaredTypeAdapter))
        {
            return declaredTypeAdapter;
        }
    }

    // In all other cases the type adapter for the runtime type is used.
    return runtimeTypeAdapter;
}
 
Example 3
Source File: MapTypeAdapterFactory.java    From framework with GNU Affero General Public License v3.0 6 votes vote down vote up
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
  Type type = typeToken.getType();

  Class<? super T> rawType = typeToken.getRawType();
  if (!Map.class.isAssignableFrom(rawType)) {
    return null;
  }

  Class<?> rawTypeOfSrc = $Gson$Types.getRawType(type);
  Type[] keyAndValueTypes = $Gson$Types.getMapKeyAndValueTypes(type, rawTypeOfSrc);
  TypeAdapter<?> keyAdapter = getKeyAdapter(gson, keyAndValueTypes[0]);
  TypeAdapter<?> valueAdapter = gson.getAdapter(TypeToken.get(keyAndValueTypes[1]));
  ObjectConstructor<T> constructor = constructorConstructor.get(typeToken);

  @SuppressWarnings({"unchecked", "rawtypes"})
  // we don't define a type parameter for the key or value types
  TypeAdapter<T> result = new Adapter(gson, keyAndValueTypes[0], keyAdapter,
      keyAndValueTypes[1], valueAdapter, constructor);
  return result;
}
 
Example 4
Source File: MapTypeAdapterFactory.java    From gson with Apache License 2.0 6 votes vote down vote up
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
  Type type = typeToken.getType();

  Class<? super T> rawType = typeToken.getRawType();
  if (!Map.class.isAssignableFrom(rawType)) {
    return null;
  }

  Class<?> rawTypeOfSrc = $Gson$Types.getRawType(type);
  Type[] keyAndValueTypes = $Gson$Types.getMapKeyAndValueTypes(type, rawTypeOfSrc);
  TypeAdapter<?> keyAdapter = getKeyAdapter(gson, keyAndValueTypes[0]);
  TypeAdapter<?> valueAdapter = gson.getAdapter(TypeToken.get(keyAndValueTypes[1]));
  ObjectConstructor<T> constructor = constructorConstructor.get(typeToken);

  @SuppressWarnings({"unchecked", "rawtypes"})
  // we don't define a type parameter for the key or value types
  TypeAdapter<T> result = new Adapter(gson, keyAndValueTypes[0], keyAdapter,
      keyAndValueTypes[1], valueAdapter, constructor);
  return result;
}
 
Example 5
Source File: XorTypeAdapterFactory.java    From salt-netapi-client with MIT License 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <A> TypeAdapter<A> create(Gson gson, TypeToken<A> typeToken) {
    Type type = typeToken.getType();
    boolean isXor = typeToken.getRawType() == Xor.class;
    boolean isParameterized = type instanceof ParameterizedType;
    boolean isSSHResult = ResultSSHResultTypeAdapterFactory.isResultSSHResult(type);
    if (isXor && isParameterized && !isSSHResult) {
        Type leftType = ((ParameterizedType) type).getActualTypeArguments()[0];
        Type rightType = ((ParameterizedType) type).getActualTypeArguments()[1];
        TypeAdapter<?> rightAdapter = gson.getAdapter(TypeToken.get(rightType));
        if (leftType.equals(SaltError.class)) {
            return (TypeAdapter<A>) errorAdapter(rightAdapter);
        }

        TypeAdapter<?> leftAdapter = gson.getAdapter(TypeToken.get(leftType));
        return (TypeAdapter<A>) xorAdapter(leftAdapter, rightAdapter);
    } else {
        return null;
    }
}
 
Example 6
Source File: ReflectiveTypeAdapterFactory.java    From letv with Apache License 2.0 6 votes vote down vote up
private Map<String, BoundField> getBoundFields(Gson context, TypeToken<?> type, Class<?> raw) {
    Map<String, BoundField> result = new LinkedHashMap();
    if (!raw.isInterface()) {
        Type declaredType = type.getType();
        while (raw != Object.class) {
            for (Field field : raw.getDeclaredFields()) {
                boolean serialize = excludeField(field, true);
                boolean deserialize = excludeField(field, false);
                if (serialize || deserialize) {
                    field.setAccessible(true);
                    BoundField boundField = createBoundField(context, field, getFieldName(field), TypeToken.get(C$Gson$Types.resolve(type.getType(), raw, field.getGenericType())), serialize, deserialize);
                    BoundField previous = (BoundField) result.put(boundField.name, boundField);
                    if (previous != null) {
                        throw new IllegalArgumentException(declaredType + " declares multiple JSON fields named " + previous.name);
                    }
                }
            }
            type = TypeToken.get(C$Gson$Types.resolve(type.getType(), raw, raw.getGenericSuperclass()));
            raw = type.getRawType();
        }
    }
    return result;
}
 
Example 7
Source File: MapTypeAdapterFactory.java    From letv with Apache License 2.0 5 votes vote down vote up
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    Type type = typeToken.getType();
    if (!Map.class.isAssignableFrom(typeToken.getRawType())) {
        return null;
    }
    Type[] keyAndValueTypes = C$Gson$Types.getMapKeyAndValueTypes(type, C$Gson$Types.getRawType(type));
    return new Adapter(gson, keyAndValueTypes[0], getKeyAdapter(gson, keyAndValueTypes[0]), keyAndValueTypes[1], gson.getAdapter(TypeToken.get(keyAndValueTypes[1])), this.constructorConstructor.getConstructor(typeToken));
}
 
Example 8
Source File: ArrayTypeAdapter.java    From gson with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
  Type type = typeToken.getType();
  if (!(type instanceof GenericArrayType || type instanceof Class && ((Class<?>) type).isArray())) {
    return null;
  }

  Type componentType = $Gson$Types.getArrayComponentType(type);
  TypeAdapter<?> componentTypeAdapter = gson.getAdapter(TypeToken.get(componentType));
  return new ArrayTypeAdapter(
          gson, componentTypeAdapter, $Gson$Types.getRawType(componentType));
}
 
Example 9
Source File: GsonJsonMarshallerFactory.java    From softlayer-java with MIT License 5 votes vote down vote up
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    if (!List.class.isAssignableFrom(type.getRawType()) || !(type.getType() instanceof ParameterizedType)) {
        return null;
    }
    Type[] typeArgs = ((ParameterizedType) type.getType()).getActualTypeArguments();
    if (typeArgs.length != 1 || !(typeArgs[0] instanceof Class)) {
        return null;
    }
    return new ListOrSingleObjectTypeAdapter(gson.getDelegateAdapter(this, type),
        gson.getAdapter((Class) typeArgs[0]));
}
 
Example 10
Source File: ResponseTypeAdapterFactoy.java    From sana.mobile with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    Type type = typeToken.getType();
    if (typeToken.getRawType() != Response.class
            || !(type instanceof ParameterizedType)) {
        return null;
    }
    Type msgType = ((ParameterizedType) type).getActualTypeArguments()[0];
    TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(msgType));
    return (TypeAdapter<T>) newResponseAdapter(adapter);
}
 
Example 11
Source File: ProducerRawRecordsTest.java    From zerocode with Apache License 2.0 5 votes vote down vote up
public static Type getType(String typeName) {
    try {
        Class<?> clazz = Class.forName(typeName);
        TypeToken<?> typeToken = TypeToken.get(clazz);
        return typeToken.getType();
    } catch (ClassNotFoundException ce) {
        throw new IllegalArgumentException("Unsupported type: " + typeName + " - " + ce);
    }
}
 
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: OptionalTypeAdapterFactory.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <A> TypeAdapter<A> create(Gson gson, TypeToken<A> typeToken) {
    Type type = typeToken.getType();
    boolean isOptional = typeToken.getRawType() == Optional.class;
    boolean isParameterized = type instanceof ParameterizedType;
    if (isOptional && isParameterized) {
        Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0];
        TypeAdapter<?> elementAdapter = gson.getAdapter(TypeToken.get(elementType));
        return (TypeAdapter<A>) optionalAdapter(elementAdapter);
    }
    else {
        return null;
    }
}
 
Example 14
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 15
Source File: TreeTypeAdapter.java    From letv with Apache License 2.0 4 votes vote down vote up
public static TypeAdapterFactory newFactoryWithMatchRawType(TypeToken<?> exactType, Object typeAdapter) {
    return new SingleTypeFactory(typeAdapter, exactType, exactType.getType() == exactType.getRawType(), null);
}
 
Example 16
Source File: ConstructorConstructor.java    From framework with GNU Affero General Public License v3.0 4 votes vote down vote up
public <T> ObjectConstructor<T> get(TypeToken<T> typeToken) {
  final Type type = typeToken.getType();
  final Class<? super T> rawType = typeToken.getRawType();

  // first try an instance creator

  @SuppressWarnings("unchecked") // types must agree
  final InstanceCreator<T> typeCreator = (InstanceCreator<T>) instanceCreators.get(type);
  if (typeCreator != null) {
    return new ObjectConstructor<T>() {
      public T construct() {
        return typeCreator.createInstance(type);
      }
    };
  }

  // Next try raw type match for instance creators
  @SuppressWarnings("unchecked") // types must agree
  final InstanceCreator<T> rawTypeCreator =
      (InstanceCreator<T>) instanceCreators.get(rawType);
  if (rawTypeCreator != null) {
    return new ObjectConstructor<T>() {
      public T construct() {
        return rawTypeCreator.createInstance(type);
      }
    };
  }

  ObjectConstructor<T> defaultConstructor = newDefaultConstructor(rawType);
  if (defaultConstructor != null) {
    return defaultConstructor;
  }

  ObjectConstructor<T> defaultImplementation = newDefaultImplementationConstructor(type, rawType);
  if (defaultImplementation != null) {
    return defaultImplementation;
  }

  // finally try unsafe
  return newUnsafeAllocator(type, rawType);
}
 
Example 17
Source File: CharacterJsonMapper.java    From Game-of-Thrones with Apache License 2.0 4 votes vote down vote up
public List<GoTCharacter> transformList(String characterJsonList) throws JsonSyntaxException {
  TypeToken<ArrayList<JSONGoTCharacter>> typeToken = new TypeToken<ArrayList<JSONGoTCharacter>>() {
  };
  Type listType = typeToken.getType();
  return getCharacters(characterJsonList, listType);
}
 
Example 18
Source File: HarvesterAnimationStateMachine.java    From EmergingTechnology with MIT License 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
@Nullable
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    if (type.getRawType() != ImmutableMultimap.class || !(type.getType() instanceof ParameterizedType)) {
        return null;
    }
    final Type[] typeArguments = ((ParameterizedType) type.getType()).getActualTypeArguments();
    if (typeArguments.length != 2 || typeArguments[0] != String.class || typeArguments[1] != String.class) {
        return null;
    }
    final TypeAdapter<Map<String, Collection<String>>> mapAdapter = gson
            .getAdapter(new TypeToken<Map<String, Collection<String>>>() {
            });
    final TypeAdapter<Collection<String>> collectionAdapter = gson
            .getAdapter(new TypeToken<Collection<String>>() {
            });
    return (TypeAdapter<T>) new TypeAdapter<ImmutableMultimap<String, String>>() {
        @Override
        public void write(JsonWriter out, ImmutableMultimap<String, String> value) throws IOException {
            mapAdapter.write(out, value.asMap());
        }

        @Override
        public ImmutableMultimap<String, String> read(JsonReader in) throws IOException {
            ImmutableMultimap.Builder<String, String> builder = ImmutableMultimap.builder();
            in.beginObject();
            while (in.hasNext()) {
                String key = in.nextName();
                switch (in.peek()) {
                    case STRING:
                        builder.put(key, in.nextString());
                        break;
                    case BEGIN_ARRAY:
                        builder.putAll(key, collectionAdapter.read(in));
                        break;
                    default:
                        throw new JsonParseException("Expected String or Array, got " + in.peek());
                }
            }
            in.endObject();
            return builder.build();
        }
    };
}
 
Example 19
Source File: ConstructorConstructor.java    From gson with Apache License 2.0 4 votes vote down vote up
public <T> ObjectConstructor<T> get(TypeToken<T> typeToken) {
  final Type type = typeToken.getType();
  final Class<? super T> rawType = typeToken.getRawType();

  // first try an instance creator

  @SuppressWarnings("unchecked") // types must agree
  final InstanceCreator<T> typeCreator = (InstanceCreator<T>) instanceCreators.get(type);
  if (typeCreator != null) {
    return new ObjectConstructor<T>() {
      @Override public T construct() {
        return typeCreator.createInstance(type);
      }
    };
  }

  // Next try raw type match for instance creators
  @SuppressWarnings("unchecked") // types must agree
  final InstanceCreator<T> rawTypeCreator =
      (InstanceCreator<T>) instanceCreators.get(rawType);
  if (rawTypeCreator != null) {
    return new ObjectConstructor<T>() {
      @Override public T construct() {
        return rawTypeCreator.createInstance(type);
      }
    };
  }

  ObjectConstructor<T> defaultConstructor = newDefaultConstructor(rawType);
  if (defaultConstructor != null) {
    return defaultConstructor;
  }

  ObjectConstructor<T> defaultImplementation = newDefaultImplementationConstructor(type, rawType);
  if (defaultImplementation != null) {
    return defaultImplementation;
  }

  // finally try unsafe
  return newUnsafeAllocator(type, rawType);
}
 
Example 20
Source File: ErrorHandlingOkCallback.java    From edx-app-android with Apache License 2.0 3 votes vote down vote up
/**
 * Create a new instance of this class.
 *
 * @param context A Context for resolving the error message strings.
 * @param responseBodyTypeToken The response body type token.
 * @param progressCallback The callback to invoke on start and finish of the request. Note that
 *                         since no callback method in this class is invoked upon request
 *                         initiation, it assumes that it's being initiated immediately, and
 *                         thus invokes that start callback immediately as well.
 * @param errorNotification The notification display to invoke upon encountering an error.
 */
public ErrorHandlingOkCallback(@NonNull final Context context,
                               @NonNull final TypeToken<T> responseBodyTypeToken,
                               @Nullable final TaskProgressCallback progressCallback,
                               @Nullable final ErrorNotification errorNotification) {
    this(context, responseBodyTypeToken.getType(), progressCallback, errorNotification, null, null);
}