Java 类com.google.gson.reflect.TypeToken 实例源码

项目:avaire    文件:PlaylistTransformer.java   
public PlaylistTransformer(DataRow data) {
    super(data);

    if (hasData()) {
        id = data.getInt("id");
        size = data.getInt("size");
        guildId = data.getLong("guild_id");
        name = data.getString("name");

        if (data.has("songs") && data.getString("songs").length() > 0) {
            List<PlaylistSong> songs = AvaIre.GSON.fromJson(data.getString("songs"), (new TypeToken<List<PlaylistSong>>() {
            }.getType()));

            if (!songs.isEmpty()) {
                this.songs.addAll(songs);
            }
        }
    }
}
项目:ObjectBoxDebugBrowser    文件:RequestHandler.java   
private String addTableDataAndGetResponse(String route) {
    UpdateRowResponse response;
    try {
        Uri uri = Uri.parse(URLDecoder.decode(route, "UTF-8"));
        String tableName = uri.getQueryParameter("tableName");
        String updatedData = uri.getQueryParameter("addData");
        List<RowDataRequest> rowDataRequests = mGson.fromJson(updatedData, new TypeToken<List<RowDataRequest>>() {
        }.getType());

        response = DatabaseHelper.addRow(null, tableName, rowDataRequests);
        return mGson.toJson(response);
    } catch (Exception e) {
        e.printStackTrace();
        response = new UpdateRowResponse();
        response.isSuccessful = false;
        return mGson.toJson(response);
    }
}
项目:Jenisys3    文件:BanList.java   
public void load() {
    this.list = new LinkedHashMap<>();
    File file = new File(this.file);
    try {
        if (!file.exists()) {
            file.createNewFile();
            this.save();
        } else {

            LinkedList<TreeMap<String, String>> list = new Gson().fromJson(Utils.readFile(this.file), new TypeToken<LinkedList<TreeMap<String, String>>>() {
            }.getType());
            for (TreeMap<String, String> map : list) {
                BanEntry entry = BanEntry.fromMap(map);
                this.list.put(entry.getName(), entry);
            }
        }
    } catch (IOException e) {
        MainLogger.getLogger().error("Could not load ban list: ", e);
    }

}
项目:android-apps    文件:WeatherActivity.java   
public List<CityData> getCityInfo() {
  if (citys.size() == 0) {
    try {
      InputStreamReader inputStreamReader = new InputStreamReader(getAssets().open("china_city_id.json"));
      BufferedReader bufferedReader = new BufferedReader(
          inputStreamReader);
      String line;
      StringBuilder stringBuilder = new StringBuilder();
      while ((line = bufferedReader.readLine()) != null) {
        stringBuilder.append(line);
      }
      bufferedReader.close();
      inputStreamReader.close();
      String json = stringBuilder.toString();
      citys = GsonUtil.getInstance().fromJson(json, new TypeToken<List<CityData>>() {
      }.getType());
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  return citys;
}
项目:FriendBook    文件:DataManager.java   
/**
 * 获取小说列表
 *
 * @param page     页码
 * @param size     每页的条目数
 * @param bookType 图书类别ID ,传0为获取全部
 */
public Observable<DataList<Book>> getBookList(long bookType, int page, int size) {
    HashMap<String, Object> hashMap = new HashMap<>();
    hashMap.put("page_index", page);
    hashMap.put("page_size", size);
    if (bookType > 0) hashMap.put("book_type", bookType);
    return RequestClient
            .getServerAPI()
            .getBookList(hashMap)
            .map(new HttpResultFunc<DataList<Book>>())
            .compose(rxCache.<DataList<Book>>transformer("getBookList" + page + size + bookType, new TypeToken<DataList<Book>>() {
            }.getType(), CacheStrategy.firstCache()))
            .map(new Func1<CacheResult<DataList<Book>>, DataList<Book>>() {
                @Override
                public DataList<Book> call(CacheResult<DataList<Book>> cacheResult) {
                    return cacheResult.getData();
                }
            });
}
项目:toyBatis    文件:DbSession.java   
private List<Mapper> getMapperFileData(Class<? extends Object> mapper) throws IOException
{
    if (mapper.isAnnotationPresent(Mapping.class))
    {
        Mapping mapping = mapper.getAnnotation(Mapping.class);
        String mappingFilename = mapping.filename();
        String mappingContent = IOUtils.resourceToString(mappingFilename, null,
                DbSession.class.getClassLoader());
        if (mappingContent != null && !mappingContent.isEmpty())
        {
            Type mapperListType = new TypeToken<ArrayList<Mapper>>(){}.getType();
            List<Mapper> mapperList = gson.fromJson(mappingContent, mapperListType);
            return mapperList;
        }
    }
    return null;
}
项目:module-template    文件:Unit2CreationTests.java   
@DataProvider
public Iterator<Object[]> validUnits2FromJson() throws IOException {
    String json = "";

    try (BufferedReader reader = new BufferedReader(new FileReader(new File("src/test/resources/units2.json")))) {
        String line = reader.readLine();
        while (line != null) {
            json += line;
            line = reader.readLine();
        }
    }

    Gson gson = new Gson();
    List<Unit2Data> units2 = gson.fromJson(json, new TypeToken<List<Unit2Data>>(){}.getType()); // like a List<Unit2Data>.class
    return units2.stream().map((g) -> new Object[] {g}).collect(Collectors.toList()).iterator();
}
项目:hauth-java    文件:OrgController.java   
@RequestMapping(value = "/delete", method = RequestMethod.POST)
public String delete(HttpServletResponse response, HttpServletRequest request) {
    String json = request.getParameter("JSON");
    List<OrgEntity> list = new GsonBuilder().create().fromJson(json,
            new TypeToken<List<OrgEntity>>() {
            }.getType());
    ;
    for (OrgEntity m : list) {

        String orgId = m.getOrg_id();
        String domainId = m.getDomain_id();

        AuthDTO authDTO = authService.domainAuth(request, domainId, "w");
        if (!authDTO.getStatus()) {
            return Hret.error(403, "您没有权限删除域【" + domainId + "】中的机构信息", null);
        }
    }

    RetMsg retMsg = orgService.delete(list);
    if (retMsg.checkCode()) {
        return Hret.success(retMsg);
    }
    response.setStatus(retMsg.getCode());
    return Hret.error(retMsg);
}
项目:Hitalk    文件:ExampleUnitTest.java   
@Test
public void testGson() throws ClassNotFoundException {
   /* B b = new B();
    b.b = "b";
    b.a = "a";
    String json = new Gson().toJson(b);
    A a = new Gson().fromJson(json,A.class);
    *//*A a1 = (A) new Gson().fromJson(json,Class.forName(a.className));*//*
    b = (B) a;*/
    HashMap<String,Integer> entries = new HashMap<>();
    entries.put("abc",1);

    System.out.println(new Gson().toJson(entries));

    HashMap hashMap = new Gson().fromJson(new Gson().toJson(entries), entries.getClass());

    Type type = new TypeToken<HashMap<String, Integer>>() {
    }.getType();
   // System.out.println(new Gson().fromJson(new Gson().toJson(entries), type));


}
项目:CouponsTracker    文件:ImportFromDriveService.java   
/**
 * Returns a {@link ContentValues} array of all the coupons in the
 * coupons JSON.
 */
private ContentValues[] getContentValuesArray(String couponsJson) {
    Gson gson = new Gson();
    /*
    Convert the json representation of the coupon data to an arrayList
    of coupons. Logic to perform this taken from:
    https://github.com/google/gson/blob/master/UserGuide.md#TOC-Serializing-and-Deserializing-Generic-Types
     */
    Type collectionType = new TypeToken<ArrayList<Coupon>>(){}.getType();
    ArrayList<Coupon> coupons = gson.fromJson(couponsJson, collectionType);
    ContentValues[] contentValuesArray = new ContentValues[coupons.size()];
    for (int i = 0; i < contentValuesArray.length; i++) {
        contentValuesArray[i] = Coupon.getContentValues(coupons.get(i));
    }
    return contentValuesArray;
}
项目:boohee_v5.6    文件:Gson.java   
public <T> T fromJson(JsonReader reader, Type typeOfT) throws JsonIOException,
        JsonSyntaxException {
    boolean isEmpty = true;
    boolean oldLenient = reader.isLenient();
    reader.setLenient(true);
    try {
        reader.peek();
        isEmpty = false;
        T object = getAdapter(TypeToken.get(typeOfT)).read(reader);
        reader.setLenient(oldLenient);
        return object;
    } catch (Throwable e) {
        if (isEmpty) {
            reader.setLenient(oldLenient);
            return null;
        }
        throw new JsonSyntaxException(e);
    } catch (Throwable e2) {
        throw new JsonSyntaxException(e2);
    } catch (Throwable e22) {
        throw new JsonSyntaxException(e22);
    } catch (Throwable th) {
        reader.setLenient(oldLenient);
    }
}
项目:CommonsLab    文件:StorageUtil.java   
public ArrayList<FeedItem> retrieveRSS_Feed(MediaType mediaType) {
    if (mediaType == MediaType.PICTURE) {
        preferences = context.getSharedPreferences(context.getString(R.string.Picture_of_the_day), Context.MODE_PRIVATE);
    } else {
        preferences = context.getSharedPreferences(context.getString(R.string.Media_of_the_day), Context.MODE_PRIVATE);
    }

    //Check if the feed is valid
    if (!preferences.getString("Date", "").equals(new Today().date())) return null;

    Gson gson = new Gson();
    String json = preferences.getString("RSS_Feed", null);
    Type type = new TypeToken<ArrayList<FeedItem>>() {
    }.getType();
    return gson.fromJson(json, type);
}
项目:Regalia    文件:GsonRealmListTest.java   
@Test
public void parse() throws Exception {
    String json = TestUtil.getCatWithListOfFriendsJson();
    Type catRealmListType = new TypeToken<RealmList<Cat>>(){}.getType();
    CatListConverter catRealmListConverter = new CatListConverter();
    Gson gson = new GsonBuilder()
            .registerTypeAdapter(catRealmListType, catRealmListConverter)
            .create();
    Cat cat = gson.fromJson(json, Cat.class);
    Assert.assertNotNull(cat);
    Assert.assertNotNull(cat.friends);
}
项目:mazes_and_minotaurs    文件:CharacterSerializer.java   
@Override
public JsonElement serialize(PlayerCharacter src, Type typeOfSrc, JsonSerializationContext context) {
    BaseClass characterClass = src.getCharClass();
    characterClass.setCharacter(null);

    Type equipListType = new TypeToken<ArrayList<Equipment>>() {
    }.getType();
    Type moneyMapType = new TypeToken<HashMap<Money, Integer>>() {
    }.getType();

    JsonObject rootObject = new JsonObject();
    rootObject.add("mScores", context.serialize(src.getScores()));
    rootObject.add("mCharClass", context.serialize(src.getCharClass(), BaseClass.class));
    rootObject.add("mGender", context.serialize(src.getGender()));
    rootObject.add("mMoney", context.serialize(src.getMoney(), moneyMapType));
    rootObject.add("mAge", context.serialize(src.getAge()));
    rootObject.add("mName", context.serialize(src.getName()));
    System.out.println(getGson().toJsonTree(src.getInventory(), equipListType));
    rootObject.add("mInventory", getGson().toJsonTree(src.getInventory(), equipListType));
    rootObject.add("mCurrentWeapon", context.serialize(src.getCurrentWeapon()));
    rootObject.add("mHelmet", context.serialize(src.getHelmet()));
    rootObject.add("mBreastplate", context.serialize(src.getBreastplate()));
    rootObject.add("mShield", context.serialize(src.getShield()));
    rootObject.add("mPatron", context.serialize(src.getPatron()));

    JsonElement classJson = context.serialize(characterClass);
    rootObject.add("mCharClass", classJson);

    characterClass.setCharacter(src);
    return rootObject;
}
项目:nifi-swagger-client    文件:FunnelApi.java   
/**
 * Gets a funnel (asynchronously)
 * 
 * @param id The funnel id. (required)
 * @param callback The callback to be executed when the API call finishes
 * @return The request call
 * @throws ApiException If fail to process the API call, e.g. serializing the request body object
 */
public com.squareup.okhttp.Call getFunnelAsync(String id, final ApiCallback<FunnelEntity> callback) throws ApiException {

    ProgressResponseBody.ProgressListener progressListener = null;
    ProgressRequestBody.ProgressRequestListener progressRequestListener = null;

    if (callback != null) {
        progressListener = new ProgressResponseBody.ProgressListener() {
            @Override
            public void update(long bytesRead, long contentLength, boolean done) {
                callback.onDownloadProgress(bytesRead, contentLength, done);
            }
        };

        progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
            @Override
            public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
                callback.onUploadProgress(bytesWritten, contentLength, done);
            }
        };
    }

    com.squareup.okhttp.Call call = getFunnelValidateBeforeCall(id, progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<FunnelEntity>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
项目:train-simulator    文件:SocketSession.java   
public String getResponse(String message) {

    /*if (message.equals("start trains")) {
      sim.startTrains();
      return "OK";
    }*/

    SimulationController simulation = SimulationController.getInstance();
    /*if (simulation.isKilled()) {
      simulation = SimulationController.newInstance();
    }*/
    logger.info("message: {}", message);

    try {
      Type stringStringMap = new TypeToken<Map<String, String>>() {
      }.getType();
      Map<String, String> map = gson.fromJson(message, stringStringMap);

      if (map.containsKey("command")) {
        return CommandHelper.processCommand(simulation, map, this) ? "OK" : "FAIL";
      }
      if (map.containsKey("type") && map.get("type").equals("set")) {
        return CommandHelper.processSetCommand(simulation, map) ? "OK" : "FAIL";
      }
    } catch (com.google.gson.JsonSyntaxException ex) {
      // wasn't json
      ex.printStackTrace();
    }

    return "echo: " + message;
  }
项目:nifi-swagger-client    文件:FlowApi.java   
/**
 * Retrieves the types of processors that this NiFi supports (asynchronously)
 * Note: This endpoint is subject to change as NiFi and it&#39;s REST API evolve.
 * @param bundleGroupFilter If specified, will only return types that are a member of this bundle group. (optional)
 * @param bundleArtifactFilter If specified, will only return types that are a member of this bundle artifact. (optional)
 * @param type If specified, will only return types whose fully qualified classname matches. (optional)
 * @param callback The callback to be executed when the API call finishes
 * @return The request call
 * @throws ApiException If fail to process the API call, e.g. serializing the request body object
 */
public com.squareup.okhttp.Call getProcessorTypesAsync(String bundleGroupFilter, String bundleArtifactFilter, String type, final ApiCallback<ProcessorTypesEntity> callback) throws ApiException {

    ProgressResponseBody.ProgressListener progressListener = null;
    ProgressRequestBody.ProgressRequestListener progressRequestListener = null;

    if (callback != null) {
        progressListener = new ProgressResponseBody.ProgressListener() {
            @Override
            public void update(long bytesRead, long contentLength, boolean done) {
                callback.onDownloadProgress(bytesRead, contentLength, done);
            }
        };

        progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
            @Override
            public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
                callback.onUploadProgress(bytesWritten, contentLength, done);
            }
        };
    }

    com.squareup.okhttp.Call call = getProcessorTypesValidateBeforeCall(bundleGroupFilter, bundleArtifactFilter, type, progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<ProcessorTypesEntity>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
项目:Farmacias    文件:PreferencesManagerImp.java   
@Override
public HashMap<String, Integer> getColorMap() {
    if(mPrefs.contains(COLOR_MAP_KEY)) {
        String jsonString = mPrefs.getString(COLOR_MAP_KEY, null);
        if(jsonString !=null) {
            java.lang.reflect.Type type = new TypeToken<HashMap<String, Integer>>(){}.getType();
            return  new Gson().fromJson(jsonString,type);
        }
    }
    return null;
}
项目:swaggy-jenkins    文件:BlueOceanApi.java   
/**
 *  (asynchronously)
 * Retrieve SCM details for an organization
 * @param organization Name of the organization (required)
 * @param scm Name of SCM (required)
 * @param callback The callback to be executed when the API call finishes
 * @return The request call
 * @throws ApiException If fail to process the API call, e.g. serializing the request body object
 */
public com.squareup.okhttp.Call getSCMAsync(String organization, String scm, final ApiCallback<GithubScm> callback) throws ApiException {

    ProgressResponseBody.ProgressListener progressListener = null;
    ProgressRequestBody.ProgressRequestListener progressRequestListener = null;

    if (callback != null) {
        progressListener = new ProgressResponseBody.ProgressListener() {
            @Override
            public void update(long bytesRead, long contentLength, boolean done) {
                callback.onDownloadProgress(bytesRead, contentLength, done);
            }
        };

        progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
            @Override
            public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
                callback.onUploadProgress(bytesWritten, contentLength, done);
            }
        };
    }

    com.squareup.okhttp.Call call = getSCMValidateBeforeCall(organization, scm, progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<GithubScm>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
项目:nifi-swagger-client    文件:AccessApi.java   
/**
 * Retrieves the access configuration for this NiFi (asynchronously)
 * 
 * @param callback The callback to be executed when the API call finishes
 * @return The request call
 * @throws ApiException If fail to process the API call, e.g. serializing the request body object
 */
public com.squareup.okhttp.Call getLoginConfigAsync(final ApiCallback<AccessConfigurationEntity> callback) throws ApiException {

    ProgressResponseBody.ProgressListener progressListener = null;
    ProgressRequestBody.ProgressRequestListener progressRequestListener = null;

    if (callback != null) {
        progressListener = new ProgressResponseBody.ProgressListener() {
            @Override
            public void update(long bytesRead, long contentLength, boolean done) {
                callback.onDownloadProgress(bytesRead, contentLength, done);
            }
        };

        progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
            @Override
            public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
                callback.onUploadProgress(bytesWritten, contentLength, done);
            }
        };
    }

    com.squareup.okhttp.Call call = getLoginConfigValidateBeforeCall(progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<AccessConfigurationEntity>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
项目:GitHub    文件:GsonParserFactory.java   
@Override
public HashMap<String, String> getStringMap(Object object) {
    try {
        Type type = new TypeToken<HashMap<String, String>>() {
        }.getType();
        return gson.fromJson(gson.toJson(object), type);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return new HashMap<>();
}
项目:happy-news    文件:NotificationSettingsActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_notification_settings);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    setTitle(R.string.title_settings_notification);
    notificationListView = (ListView) findViewById(R.id.notificationListView);

    preferences = getApplicationContext().getSharedPreferences(
        getString(R.string.preference_file_key), Context.MODE_PRIVATE);

    addNotificationFab = (FloatingActionButton) findViewById(R.id.timePickerFAB);
    addNotificationFab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DialogFragment newFragment = new TimePickerFragment();
            newFragment.show(getFragmentManager(), "timePicker");
        }
    });

    notifications = new ArrayList<>();
    String notificationsGsonString = preferences.getString(getString(R.string.preference_notifications), "");
    Type type = new TypeToken<List<NotificationSetting>>() {
    }.getType();
    if (!notificationsGsonString.equals("")) {
        notifications = new Gson().fromJson(notificationsGsonString, type);
    }
    refreshList();
}
项目:afp-api-client    文件:ClusterApi.java   
/**
 * Word cluster (asynchronously)
 * Return the word cluster from a search
 * @param parameters parameters (required)
 * @param callback The callback to be executed when the API call finishes
 * @return The request call
 * @throws ApiException If fail to process the API call, e.g. serializing the request body object
 */
public com.squareup.okhttp.Call clusterUsingPOST1Async(Parameters parameters, final ApiCallback<ReponseCluster> callback) throws ApiException {

    ProgressResponseBody.ProgressListener progressListener = null;
    ProgressRequestBody.ProgressRequestListener progressRequestListener = null;

    if (callback != null) {
        progressListener = new ProgressResponseBody.ProgressListener() {
            @Override
            public void update(long bytesRead, long contentLength, boolean done) {
                callback.onDownloadProgress(bytesRead, contentLength, done);
            }
        };

        progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
            @Override
            public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
                callback.onUploadProgress(bytesWritten, contentLength, done);
            }
        };
    }

    com.squareup.okhttp.Call call = clusterUsingPOST1Call(parameters, progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<ReponseCluster>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
项目:ease-volley-wrapper    文件:EaseRequest.java   
RequestBuilder(TypeToken<EaseResponse<K>> typeToken) {
    method = Request.Method.GET;
    runInBackground = false;
    this.typeToken = typeToken;
    this.shouldCache = -1; // fall back to default
    this.socketTimeout = -1; // fall back to default
}
项目:Nyris.IMX.Android    文件:ObjectProposalTask.java   
/**
 * Evaluate the content of response
 * @param content of type Object it could be ErrorResponse or a String
 */
@Override
protected void onPostExecute(Object content) {
    if(callback == null)
        return;
    if(content instanceof ResponseError){
        ResponseError responseError = (ResponseError) content;
        callback.onError(responseError);
    }
    else{
        String strContent = (String) content;
        try {
            Gson gson = new Gson();
            List<ObjectProposal> objectProposals = gson.fromJson(strContent, new TypeToken<List<ObjectProposal>>(){}.getType());
            if(objectProposals != null){
                callback.onObjectExtracted(objectProposals);
            }
            else {
                responseError.setErrorCode(ResponseCode.OBJECT_NOT_FOUND_ERROR);
                responseError.setErrorDescription(context.getText(R.string.error_object_not_found).toString());
                callback.onError(responseError);
            }
        }
        catch (Exception e){
            e.printStackTrace();
            responseError.setErrorCode(ResponseCode.UNKNOWN_ERROR);
            responseError.setErrorDescription(e.getMessage());
            callback.onError(responseError);
        }
    }
}
项目:letv    文件:Gson.java   
public <T> TypeAdapter<T> getNextAdapter(Gson gson, TypeAdapterFactory skipPast, TypeToken<T> type) {
    boolean skipPastFound = false;
    for (TypeAdapterFactory factory : gson.factories) {
        if (skipPastFound) {
            TypeAdapter<T> candidate = factory.create(gson, type);
            if (candidate != null) {
                return candidate;
            }
        } else if (factory == skipPast) {
            skipPastFound = true;
        }
    }
    throw new IllegalArgumentException("GSON cannot serialize " + type);
}
项目:boohee_v5.6    文件:Food.java   
public static ArrayList<Food> parseFoods(JSONObject res) {
    ArrayList<Food> foods = null;
    try {
        return (ArrayList) new Gson().fromJson(res.optJSONArray("foods").toString(), new TypeToken<ArrayList<Food>>() {
        }.getType());
    } catch (Exception e) {
        e.printStackTrace();
        return foods;
    }
}
项目:RestClient    文件:RestTestInteractorImpl.java   
@Override
public void saveRestTest(RestTest test) {
    Settings settings = RestClientApplication.getSettings();
    String value = settings.get(key);
    List<RestTest> result = new ArrayList<>();
    int pos = -1;
    if (null != value) {
        Gson gson = new Gson();
        result = gson.fromJson(value, new TypeToken<List<RestTest>>() {
        }.getType());
        int size = result.size();
        for (int i = 0; i < size; i++) {
            RestTest temp = result.get(i);
            if (temp.getId().equals(test.getId())) {
                pos = i;
                break;
            }
        }

    }
    if (pos != -1) {
        result.set(pos, test);
    } else {
        result.add(0, test);
    }
    settings.put(key, result);
}
项目:full-javaee-app    文件:Geocode.java   
@SuppressWarnings("rawtypes")
public static String getZipFromLatLong(String latitude, String longitude) {
       String request = "https://maps.googleapis.com/maps/api/geocode/json?";
       String address = "address=";
       String coOrdinates = "latlng=";
    CustomUtilities custom = new CustomUtilities();
    String zip = "";
    String finalRequest = request + coOrdinates + latitude + "," + longitude + "&" + key;

    // To convert resulting JSON into Map
    Gson gson = new Gson();

    // Models expected JSON, very basic
    Type type = new TypeToken<Map<String, Object>>() {
    }.getType();

    // Pulls JSON from api request
    String json = custom.RequestToString(finalRequest);

    // Creates map using Gson
    Map<String, Object> map = gson.fromJson(json, type);
    ArrayList list = ((ArrayList)((LinkedTreeMap)((ArrayList) map.get("results")).get(0)).get("address_components"));

    for (Object elt : list) {
        LinkedTreeMap treeElt = (LinkedTreeMap) elt;
        String name = (String) ((ArrayList)treeElt.get("types")).get(0);

        if (name.equals("postal_code")) {
            zip = (String) (treeElt.get("short_name"));
            break;
        }
    }

    return zip == null ? " " : zip;
}
项目:nifi-swagger-client    文件:FlowApi.java   
/**
 * Generates a client id. (asynchronously)
 * 
 * @param callback The callback to be executed when the API call finishes
 * @return The request call
 * @throws ApiException If fail to process the API call, e.g. serializing the request body object
 */
public com.squareup.okhttp.Call generateClientIdAsync(final ApiCallback<String> callback) throws ApiException {

    ProgressResponseBody.ProgressListener progressListener = null;
    ProgressRequestBody.ProgressRequestListener progressRequestListener = null;

    if (callback != null) {
        progressListener = new ProgressResponseBody.ProgressListener() {
            @Override
            public void update(long bytesRead, long contentLength, boolean done) {
                callback.onDownloadProgress(bytesRead, contentLength, done);
            }
        };

        progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
            @Override
            public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
                callback.onUploadProgress(bytesWritten, contentLength, done);
            }
        };
    }

    com.squareup.okhttp.Call call = generateClientIdValidateBeforeCall(progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<String>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
项目:logistimo-web-service    文件:ReportServiceUtil.java   
protected Report constructReport(List<Field> fields, JSONArray row) throws IllegalAccessException {
  Report report = new Report();
  for (int j = 0; j < row.length(); j++) {
    Field field = fields.get(j);
    switch (field.getType().getSimpleName()) {
      case LONG:
        if (StringUtils.isNotBlank(row.getString(j))) {
          field.set(report, row.getLong(j));
        } else {
          field.set(report, 0L);
        }
        break;
      case FLOAT:
        if (StringUtils.isNotBlank(row.getString(j))) {
          field.set(report, new Float(row.getDouble(j)));
        } else {
          field.set(report, 0F);
        }
        break;
      case MAP:
        try {
          field.set(report,
              new Gson().fromJson(row.getString(j), new TypeToken<Map<String, Float>>() {
              }.getType()));
        } catch (Exception e) {
          field.set(report, new HashMap(0));
        }
        break;
      default:
        field.set(report, row.get(j));
    }
  }
  return report;
}
项目:cryptotrader    文件:BitmexContextTest.java   
@Test
public void testCancelOrders() throws Exception {

    doAnswer(i -> {

        assertEquals(i.getArgumentAt(0, RequestType.class), DELETE);
        assertEquals(i.getArgumentAt(1, String.class), "/api/v1/order");
        assertEquals(i.getArgumentAt(2, Map.class), emptyMap());
        String data = i.getArgumentAt(3, String.class);

        Map<String, Set<String>> map = new Gson().fromJson(data, new TypeToken<Map<String, Set<String>>>() {
        }.getType());
        assertEquals(map.remove("clOrdID"), Sets.newHashSet(null, "uid1"));

        return new Gson().toJson(singleton(singletonMap("clOrdID", "uid1")));

    }).when(target).executePrivate(any(), any(), any(), any());

    CancelInstruction i1 = CancelInstruction.builder().id(null).build();
    CancelInstruction i2 = CancelInstruction.builder().id("uid1").build();

    Key key = Key.builder().instrument("XBTZ17").build();
    Map<CancelInstruction, String> result = target.cancelOrders(key, Sets.newHashSet(i1, null, i2));
    assertEquals(result.size(), 2);
    assertEquals(result.get(i1), null);
    assertEquals(result.get(i2), "uid1");

}
项目:GitHub    文件:RxOperatorExampleActivity.java   
/************************************
 * flatMap and filter operator start
 ************************************/

private Observable<List<User>> getAllMyFriendsObservable() {
    return RxAndroidNetworking.get("https://fierce-cove-29863.herokuapp.com/getAllFriends/{userId}")
            .addPathParameter("userId", "1")
            .build()
            .getParseObservable(new TypeToken<List<User>>() {
            });
}
项目:HLOLI    文件:SharedPreManager.java   
/**
 * 获取搜索历史
 *
 * @param context
 * @return
 */
public List<String> getHistory(Context context) {
    SharedPreferences sp = context.getSharedPreferences(SP_TAG, Context.MODE_PRIVATE);
    String jsonData = sp.getString(HISTORY, "");
    return gson.fromJson(jsonData, new TypeToken<List<String>>() {
    }.getType());
}
项目:coner-core-client-java    文件:HandicapGroupsApi.java   
/**
 * Get all Handicap Group Sets (asynchronously)
 * 
 * @param callback The callback to be executed when the API call finishes
 * @return The request call
 * @throws ApiException If fail to process the API call, e.g. serializing the request body object
 */
public com.squareup.okhttp.Call getHandicapGroupSetsAsync(final ApiCallback<GetHandicapGroupSetsResponse> callback) throws ApiException {

    ProgressResponseBody.ProgressListener progressListener = null;
    ProgressRequestBody.ProgressRequestListener progressRequestListener = null;

    if (callback != null) {
        progressListener = new ProgressResponseBody.ProgressListener() {
            @Override
            public void update(long bytesRead, long contentLength, boolean done) {
                callback.onDownloadProgress(bytesRead, contentLength, done);
            }
        };

        progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
            @Override
            public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
                callback.onUploadProgress(bytesWritten, contentLength, done);
            }
        };
    }

    com.squareup.okhttp.Call call = getHandicapGroupSetsValidateBeforeCall(progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<GetHandicapGroupSetsResponse>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
项目:intellij-circleci-integration    文件:BuildsModelTest.java   
private List<BuildInterface> createMockBuilds() throws IOException {
    String json = IOUtils.toString(
            getClass().getResourceAsStream("/recent-builds.json"),
            Charset.defaultCharset()
    );
    Gson gson = new Gson();
    return gson.fromJson(json, new TypeToken<List<RecentBuild>>() {}.getType());
}
项目:nifi-swagger-client    文件:TenantsApi.java   
/**
 * Gets all users (asynchronously)
 * Note: This endpoint is subject to change as NiFi and it&#39;s REST API evolve.
 * @param callback The callback to be executed when the API call finishes
 * @return The request call
 * @throws ApiException If fail to process the API call, e.g. serializing the request body object
 */
public com.squareup.okhttp.Call getUsersAsync(final ApiCallback<UsersEntity> callback) throws ApiException {

    ProgressResponseBody.ProgressListener progressListener = null;
    ProgressRequestBody.ProgressRequestListener progressRequestListener = null;

    if (callback != null) {
        progressListener = new ProgressResponseBody.ProgressListener() {
            @Override
            public void update(long bytesRead, long contentLength, boolean done) {
                callback.onDownloadProgress(bytesRead, contentLength, done);
            }
        };

        progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
            @Override
            public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
                callback.onUploadProgress(bytesWritten, contentLength, done);
            }
        };
    }

    com.squareup.okhttp.Call call = getUsersValidateBeforeCall(progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<UsersEntity>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
项目:letv    文件:TypeAdapterRuntimeTypeWrapper.java   
public void write(JsonWriter out, T value) throws IOException {
    TypeAdapter chosen = this.delegate;
    Type runtimeType = getRuntimeTypeIfMoreSpecific(this.type, value);
    if (runtimeType != this.type) {
        TypeAdapter runtimeTypeAdapter = this.context.getAdapter(TypeToken.get(runtimeType));
        if (!(runtimeTypeAdapter instanceof Adapter)) {
            chosen = runtimeTypeAdapter;
        } else if (this.delegate instanceof Adapter) {
            chosen = runtimeTypeAdapter;
        } else {
            chosen = this.delegate;
        }
    }
    chosen.write(out, value);
}
项目:customstuff4    文件:ItemFilterDeserializerTest.java   
@Test
public void test_machineInput()
{
    MachineManager.addRecipe(new ResourceLocation("someMachine"), new TestMachineRecipe());
    Map<String, ItemFilter> map = gson.fromJson("{\"filter\": \"machineInput:someMachine\"}", new TypeToken<Map<String, ItemFilter>>() {}.getType());

    ItemFilter filter = map.get("filter");

    assertTrue(filter.accepts(new ItemStack(Items.STICK)));
    assertTrue(filter.accepts(new ItemStack(Items.IRON_INGOT)));
    assertFalse(filter.accepts(new ItemStack(Items.GOLD_INGOT)));
}
项目:Android-Development    文件:StorageUtil.java   
public ArrayList<ParcelablePOI> getFavoritePOIs() {
    preferences = context.getSharedPreferences(FAVORITES, Context.MODE_PRIVATE);
    String pois;
    //Get favorites that are previously stored
    if ((pois = preferences.getString("FAVORITES", null)) == null) return null;
    if (pois.equals("")) return null;//no favorites stored yet

    Gson gson = new Gson();
    Type type = new TypeToken<ArrayList<ParcelablePOI>>() {
    }.getType();
    return gson.fromJson(pois, type);
}