当前位置: 首页>>代码示例>>Java>>正文


Java TypeToken类代码示例

本文整理汇总了Java中com.google.gson.reflect.TypeToken的典型用法代码示例。如果您正苦于以下问题:Java TypeToken类的具体用法?Java TypeToken怎么用?Java TypeToken使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


TypeToken类属于com.google.gson.reflect包,在下文中一共展示了TypeToken类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: PlaylistTransformer

import com.google.gson.reflect.TypeToken; //导入依赖的package包/类
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);
            }
        }
    }
}
 
开发者ID:avaire,项目名称:avaire,代码行数:20,代码来源:PlaylistTransformer.java

示例2: addTableDataAndGetResponse

import com.google.gson.reflect.TypeToken; //导入依赖的package包/类
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);
    }
}
 
开发者ID:kosiarska,项目名称:ObjectBoxDebugBrowser,代码行数:19,代码来源:RequestHandler.java

示例3: load

import com.google.gson.reflect.TypeToken; //导入依赖的package包/类
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);
    }

}
 
开发者ID:FrontierDevs,项目名称:Jenisys3,代码行数:22,代码来源:BanList.java

示例4: getProcessorTypesAsync

import com.google.gson.reflect.TypeToken; //导入依赖的package包/类
/**
 * 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;
}
 
开发者ID:hermannpencole,项目名称:nifi-swagger-client,代码行数:37,代码来源:FlowApi.java

示例5: getCityInfo

import com.google.gson.reflect.TypeToken; //导入依赖的package包/类
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;
}
 
开发者ID:tomoya92,项目名称:android-apps,代码行数:23,代码来源:WeatherActivity.java

示例6: getBookList

import com.google.gson.reflect.TypeToken; //导入依赖的package包/类
/**
 * 获取小说列表
 *
 * @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();
                }
            });
}
 
开发者ID:z-chu,项目名称:FriendBook,代码行数:26,代码来源:DataManager.java

示例7: getMapperFileData

import com.google.gson.reflect.TypeToken; //导入依赖的package包/类
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;
}
 
开发者ID:PvtTony,项目名称:toyBatis,代码行数:18,代码来源:DbSession.java

示例8: validUnits2FromJson

import com.google.gson.reflect.TypeToken; //导入依赖的package包/类
@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();
}
 
开发者ID:SpaceHead1C,项目名称:module-template,代码行数:17,代码来源:Unit2CreationTests.java

示例9: delete

import com.google.gson.reflect.TypeToken; //导入依赖的package包/类
@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);
}
 
开发者ID:hzwy23,项目名称:hauth-java,代码行数:26,代码来源:OrgController.java

示例10: testGson

import com.google.gson.reflect.TypeToken; //导入依赖的package包/类
@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));


}
 
开发者ID:zuoweitan,项目名称:Hitalk,代码行数:23,代码来源:ExampleUnitTest.java

示例11: getContentValuesArray

import com.google.gson.reflect.TypeToken; //导入依赖的package包/类
/**
 * 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;
}
 
开发者ID:darsh2,项目名称:CouponsTracker,代码行数:20,代码来源:ImportFromDriveService.java

示例12: fromJson

import com.google.gson.reflect.TypeToken; //导入依赖的package包/类
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);
    }
}
 
开发者ID:JackChan1999,项目名称:boohee_v5.6,代码行数:26,代码来源:Gson.java

示例13: retrieveRSS_Feed

import com.google.gson.reflect.TypeToken; //导入依赖的package包/类
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);
}
 
开发者ID:CommonsLab,项目名称:CommonsLab,代码行数:17,代码来源:StorageUtil.java

示例14: parse

import com.google.gson.reflect.TypeToken; //导入依赖的package包/类
@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);
}
 
开发者ID:Commit451,项目名称:Regalia,代码行数:13,代码来源:GsonRealmListTest.java

示例15: serialize

import com.google.gson.reflect.TypeToken; //导入依赖的package包/类
@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;
}
 
开发者ID:CIS-Extra,项目名称:mazes_and_minotaurs,代码行数:32,代码来源:CharacterSerializer.java


注:本文中的com.google.gson.reflect.TypeToken类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。