@SuppressWarnings("unchecked")
  @Override
  public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    Type type = typeToken.getType();
    if (typeToken.getRawType() != ImmutableMap.class || !(type instanceof ParameterizedType)) {
      return null;
    }

    com.google.common.reflect.TypeToken<ImmutableMap<?, ?>> betterToken =
        (com.google.common.reflect.TypeToken<ImmutableMap<?, ?>>)
            com.google.common.reflect.TypeToken.of(typeToken.getType());
    final TypeAdapter<HashMap<?, ?>> hashMapAdapter =
        (TypeAdapter<HashMap<?, ?>>)
            gson.getAdapter(
                TypeToken.get(
                    betterToken.getSupertype(Map.class).getSubtype(HashMap.class).getType()));
    return new TypeAdapter<T>() {
      @Override
      public void write(JsonWriter out, T value) throws IOException {
        HashMap<?, ?> hashMap = Maps.newHashMap((Map<?, ?>) value);
        hashMapAdapter.write(out, hashMap);
      }

      @Override
      public T read(JsonReader in) throws IOException {
        HashMap<?, ?> hashMap = hashMapAdapter.read(in);
        return (T) ImmutableMap.copyOf(hashMap);
      }
    };
  }
 @Override
 protected void authenticate(IOperationMonitor monitor) throws IOException {
   UserCredentials credentials =
       getClient().getLocation().getCredentials(AuthenticationType.REPOSITORY);
   if (credentials == null) {
     throw new IllegalStateException("Authentication requested without valid credentials");
   }
   HttpRequestBase request =
       new HttpGet(
           baseUrl()
               + MessageFormat.format(
                   "/login?login={0}&password={1}",
                   new Object[] {credentials.getUserName(), credentials.getPassword()}));
   request.setHeader(CONTENT_TYPE, TEXT_XML_CHARSET_UTF_8);
   request.setHeader(ACCEPT, APPLICATION_JSON);
   HttpResponse response = getClient().execute(request, monitor);
   try {
     if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
       getClient().setAuthenticated(false);
       throw new AuthenticationException(
           "Authentication failed",
           new AuthenticationRequest<AuthenticationType<UserCredentials>>(
               getClient().getLocation(), AuthenticationType.REPOSITORY));
     } else {
       TypeToken<LoginToken> type = new TypeToken<LoginToken>() {};
       InputStream is = response.getEntity().getContent();
       InputStreamReader in = new InputStreamReader(is);
       LoginToken loginToken = new Gson().fromJson(in, type.getType());
       ((BugzillaRestHttpClient) getClient()).setLoginToken(loginToken);
       getClient().setAuthenticated(true);
     }
   } finally {
     HttpUtil.release(request, response, monitor);
   }
 }
Esempio n. 3
0
 /** Preferencesから取得したJSONをListに変換して返す */
 public static <T> List<T> getList(Context context, String key, TypeToken typeToken) {
   String jsonString = getPreferences(context).getString(key, "");
   if (TextUtils.isEmpty(jsonString)) {
     return null;
   }
   List<T> list = new Gson().fromJson(jsonString, typeToken.getType());
   return list;
 }
 public TypeAdapter create(Gson gson, TypeToken typetoken)
 {
     typetoken = typetoken.getType();
     if (!(typetoken instanceof GenericArrayType) && (!(typetoken instanceof Class) || !((Class)typetoken).isArray()))
     {
         return null;
     } else
     {
         typetoken = com.google.gson.internal.yComponentType(typetoken);
         return new ArrayTypeAdapter(gson, gson.getAdapter(TypeToken.get(typetoken)), com.google.gson.internal.ype(typetoken));
     }
 }
Esempio n. 5
0
  <T> T convertFromJsonToObjectOfType(String response, TypeToken<T> type) {
    try {

      return (T) gson.fromJson(response, type.getType());

    } catch (JsonParseException x) {
      log.warn("could not parse json", x);
    } catch (Exception x) {
      log.error("Unhandled exception!", x);
    }
    return null;
  }
  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;
        }
        field.setAccessible(true);
        Type fieldType = $Gson$Types.resolve(type.getType(), raw, field.getGenericType());
        List<String> fieldNames = getFieldNames(field);
        BoundField previous = null;
        for (int i = 0; i < fieldNames.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;
  }
  public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
    Type type = typeToken.getType();

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

    Type elementType = $Gson$Types.getCollectionElementType(type, rawType);
    TypeAdapter<?> elementTypeAdapter = gson.getAdapter(TypeToken.get(elementType));
    ObjectConstructor<T> constructor = constructorConstructor.getConstructor(typeToken);

    @SuppressWarnings({"unchecked", "rawtypes"}) // create() doesn't define a type parameter
    TypeAdapter<T> result = new Adapter(gson, elementType, elementTypeAdapter, constructor);
    return result;
  }
 public static <T> T fromJson(String json, TypeToken<T> token, String datePattern) {
   if (TextUtils.isEmpty(json)) {
     return null;
   }
   GsonBuilder builder = new GsonBuilder();
   if (TextUtils.isEmpty(datePattern)) {
     datePattern = DEFAULT_DATE_PATTERN;
   }
   /* builder.registerTypeAdapter(Map.class, new HashMapDeserializer()); */
   Gson gson = builder.create();
   try {
     return gson.fromJson(json, token.getType());
   } catch (Exception ex) {
     return null;
   }
 }
Esempio n. 9
0
  /**
   * 将给定的 {@code JSON} 字符串转换成指定的类型对象。
   *
   * @param <T> 要转换的目标类型。
   * @param json 给定的 {@code JSON} 字符串。
   * @param token {@code com.google.gson.reflect.TypeToken} 的类型指示类对象。
   * @param datePattern 日期格式模式。
   * @return 给定的 {@code JSON} 字符串表示的指定的类型对象。
   */
  public static <T> T fromJson(String json, TypeToken<T> token, String datePattern) {
    if (isEmpty(json)) {
      return null;
    }

    GsonBuilder builder = new GsonBuilder();
    if (isEmpty(datePattern)) {
      datePattern = DEFAULT_DATE_PATTERN;
    }

    Gson gson = builder.create();

    try {
      return gson.fromJson(json, token.getType());
    } catch (Exception ex) {
      return null;
    }
  }
Esempio n. 10
0
 /** json解析回ArrayList,参数为new TypeToken<ArrayList<T>>() {},必须加泛型 */
 public static List<?> jsonToList(String json, TypeToken<?> token) {
   return (List<?>) jsonToObject(json, token.getType());
 }
Esempio n. 11
0
 @Deprecated
 public boolean isAssignableFrom(TypeToken<?> typeToken) {
     return this.isAssignableFrom(typeToken.getType());
 }