com.google.gson.reflect.TypeToken Java Examples

The following examples show how to use com.google.gson.reflect.TypeToken. 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 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 #2
Source File: MessageJsonHandlerTest.java    From lsp4j with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testEnumParamNull() {
	Map<String, JsonRpcMethod> supportedMethods = new LinkedHashMap<>();
	supportedMethods.put("foo", JsonRpcMethod.request("foo",
			new TypeToken<Void>() {}.getType(),
			new TypeToken<List<MyEnum>>() {}.getType()));
	MessageJsonHandler handler = new MessageJsonHandler(supportedMethods);
	handler.setMethodProvider((id) -> "foo");
	RequestMessage message = (RequestMessage) handler.parseMessage("{\"jsonrpc\":\"2.0\","
			+ "\"id\":\"2\",\n"
			+ "\"params\": [1, 2, null],\n"
			+ "\"method\":\"foo\"\n"
			+ "}");
	Assert.assertTrue("" + message.getParams().getClass(), message.getParams() instanceof List);

	List<?> parameters = (List<?>) message.getParams();
	Assert.assertEquals(Arrays.asList(MyEnum.A, MyEnum.B, null),
			parameters);
}
 
Example #3
Source File: ResolveNuance.java    From Saiy-PS with GNU Affero General Public License v3.0 6 votes vote down vote up
public void unpack(@NonNull final JSONObject payload) {
    if (DEBUG) {
        MyLog.i(CLS_NAME, "unpacking");
    }

    final GsonBuilder builder = new GsonBuilder();
    builder.disableHtmlEscaping();
    builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);

    final Gson gson = builder.create();
    nluNuance = gson.fromJson(payload.toString(), new TypeToken<NLUNuance>() {
    }.getType());

    new NLUCoerce(getNLUNuance(), getContext(), getSupportedLanguage(), getVRLocale(), getTTSLocale(),
            getConfidenceArray(), getResultsArray()).coerce();
}
 
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: OfferPageDeserializerTest.java    From java-stellar-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeserialize() {
  Page<OfferResponse> transactionsPage = GsonSingleton.getInstance().fromJson(json, new TypeToken<Page<OfferResponse>>() {}.getType());

  assertEquals(transactionsPage.getRecords().get(0).getId(), new Long(241));
  assertEquals(transactionsPage.getRecords().get(0).getSeller(), "GA2IYMIZSAMDD6QQTTSIEL73H2BKDJQTA7ENDEEAHJ3LMVF7OYIZPXQD");
  assertEquals(transactionsPage.getRecords().get(0).getPagingToken(), "241");
  assertEquals(transactionsPage.getRecords().get(0).getSelling(), Asset.createNonNativeAsset("INR", "GA2IYMIZSAMDD6QQTTSIEL73H2BKDJQTA7ENDEEAHJ3LMVF7OYIZPXQD"));
  assertEquals(transactionsPage.getRecords().get(0).getBuying(), Asset.createNonNativeAsset("USD", "GA2IYMIZSAMDD6QQTTSIEL73H2BKDJQTA7ENDEEAHJ3LMVF7OYIZPXQD"));
  assertEquals(transactionsPage.getRecords().get(0).getAmount(), "10.0000000");
  assertEquals(transactionsPage.getRecords().get(0).getPrice(), "11.0000000");
  assertEquals(transactionsPage.getRecords().get(0).getLastModifiedLedger(), new Integer(22200794));
  assertEquals(transactionsPage.getRecords().get(0).getLastModifiedTime(), "2019-01-28T12:30:38Z");

  assertEquals(transactionsPage.getLinks().getNext().getHref(), "https://horizon-testnet.stellar.org/accounts/GA2IYMIZSAMDD6QQTTSIEL73H2BKDJQTA7ENDEEAHJ3LMVF7OYIZPXQD/offers?order=asc&limit=10&cursor=241");
  assertEquals(transactionsPage.getLinks().getPrev().getHref(), "https://horizon-testnet.stellar.org/accounts/GA2IYMIZSAMDD6QQTTSIEL73H2BKDJQTA7ENDEEAHJ3LMVF7OYIZPXQD/offers?order=desc&limit=10&cursor=241");
  assertEquals(transactionsPage.getLinks().getSelf().getHref(), "https://horizon-testnet.stellar.org/accounts/GA2IYMIZSAMDD6QQTTSIEL73H2BKDJQTA7ENDEEAHJ3LMVF7OYIZPXQD/offers?order=asc&limit=10&cursor=");
}
 
Example #6
Source File: InstanceCreatorTest.java    From gson with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public void testInstanceCreatorForParametrizedType() throws Exception {
  @SuppressWarnings("serial")
  class SubTreeSet<T> extends TreeSet<T> {}
  InstanceCreator<SortedSet> sortedSetCreator = new InstanceCreator<SortedSet>() {
    @Override public SortedSet createInstance(Type type) {
      return new SubTreeSet();
    }
  };
  Gson gson = new GsonBuilder()
      .registerTypeAdapter(SortedSet.class, sortedSetCreator)
      .create();

  Type sortedSetType = new TypeToken<SortedSet<String>>() {}.getType();
  SortedSet<String> set = gson.fromJson("[\"a\"]", sortedSetType);
  assertEquals(set.first(), "a");
  assertEquals(SubTreeSet.class, set.getClass());

  set = gson.fromJson("[\"b\"]", SortedSet.class);
  assertEquals(set.first(), "b");
  assertEquals(SubTreeSet.class, set.getClass());
}
 
Example #7
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 #8
Source File: RequestHandler.java    From AndroidDemo with MIT License 6 votes vote down vote up
private String updateTableDataAndGetResponse(String route) {
    UpdateRowResponse response;
    try {
        Uri uri = Uri.parse(URLDecoder.decode(route, "UTF-8"));
        String tableName = uri.getQueryParameter("tableName");
        String updatedData = uri.getQueryParameter("updatedData");
        List<RowDataRequest> rowDataRequests = mGson.fromJson(updatedData, new TypeToken<List<RowDataRequest>>() {
        }.getType());
        if (Constants.APP_SHARED_PREFERENCES.equals(mSelectedDatabase)) {
            response = PrefHelper.updateRow(mContext, tableName, rowDataRequests);
        } else {
            response = DatabaseHelper.updateRow(mDatabase, tableName, rowDataRequests);
        }
        return mGson.toJson(response);
    } catch (Exception e) {
        e.printStackTrace();
        response = new UpdateRowResponse();
        response.isSuccessful = false;
        return mGson.toJson(response);
    }
}
 
Example #9
Source File: CommentFragment.java    From BigApp_Discuz_Android with Apache License 2.0 6 votes vote down vote up
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mListView = (RefreshListView) inflater.inflate(R.layout.fragment_list, container, false);
    ViewUtils.inject(this, mListView);
    mListView.setMode(PullToRefreshBase.Mode.DISABLED);

    BundleData bundleData = FragmentUtils.getData(this);

    ZogUtils.printObj(CommentFragment.class, bundleData);

    Type type = new TypeToken<ArrayList<CommentField>>() {
    }.getType();
    ArrayList<CommentField> list = bundleData.getArrayList(Key.CLAN_DATA,type);

    ZogUtils.printError(CommentFragment.class, "list.size():" + list.size());

    mAdapter = new CommentAdapter(getActivity(), list);
    mListView.setAdapter(mAdapter);
    return mListView;
}
 
Example #10
Source File: TwitterAdsCardsApiImpl.java    From twitter4j-ads with MIT License 6 votes vote down vote up
@SuppressWarnings("Duplicates")
@Override
public BaseAdsListResponseIterable<TwitterWebsiteCard> getAllWebsiteCards(String accountId, List<String> cardIds, boolean withDeleted,
                                                                          Optional<Integer> count) throws TwitterException {
    TwitterAdUtil.ensureNotNull(accountId, ACCOUNT_ID);
    List<HttpParameter> params = Lists.newArrayList();
    params.add(new HttpParameter(PARAM_WITH_DELETED, withDeleted));
    if (TwitterAdUtil.isNotEmpty(cardIds)) {
        params.add(new HttpParameter(PARAM_CARD_IDS, TwitterAdUtil.getCsv(cardIds)));
    }
    if (count != null && count.isPresent()) {
        params.add(new HttpParameter(PARAM_COUNT, count.get()));
    }

    String url = twitterAdsClient.getBaseAdsAPIUrl() + PREFIX_ACCOUNTS_URI + accountId + PATH_WEBSITE_CARDS;
    Type type = new TypeToken<BaseAdsListResponse<TwitterWebsiteCard>>() {
    }.getType();
    return twitterAdsClient.executeHttpListRequest(url, params, type);
}
 
Example #11
Source File: DayuClient.java    From tencentcloud-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 *为高防包、高防IP、高防IP专业版、棋牌盾等产品设置DDoS攻击的告警通知阈值
 * @param req ModifyDDoSAlarmThresholdRequest
 * @return ModifyDDoSAlarmThresholdResponse
 * @throws TencentCloudSDKException
 */
public ModifyDDoSAlarmThresholdResponse ModifyDDoSAlarmThreshold(ModifyDDoSAlarmThresholdRequest req) throws TencentCloudSDKException{
    JsonResponseModel<ModifyDDoSAlarmThresholdResponse> rsp = null;
    try {
            Type type = new TypeToken<JsonResponseModel<ModifyDDoSAlarmThresholdResponse>>() {
            }.getType();
            rsp  = gson.fromJson(this.internalRequest(req, "ModifyDDoSAlarmThreshold"), type);
    } catch (JsonSyntaxException e) {
        throw new TencentCloudSDKException(e.getMessage());
    }
    return rsp.response;
}
 
Example #12
Source File: ServerConfigApi.java    From director-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Get server configuration (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 getAsync(final ApiCallback<Map<String, 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 = getValidateBeforeCall(progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<Map<String, String>>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
 
Example #13
Source File: OrganizationClient.java    From tencentcloud-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 *移动成员到指定企业组织单元
 * @param req MoveOrganizationMembersToNodeRequest
 * @return MoveOrganizationMembersToNodeResponse
 * @throws TencentCloudSDKException
 */
public MoveOrganizationMembersToNodeResponse MoveOrganizationMembersToNode(MoveOrganizationMembersToNodeRequest req) throws TencentCloudSDKException{
    JsonResponseModel<MoveOrganizationMembersToNodeResponse> rsp = null;
    try {
            Type type = new TypeToken<JsonResponseModel<MoveOrganizationMembersToNodeResponse>>() {
            }.getType();
            rsp  = gson.fromJson(this.internalRequest(req, "MoveOrganizationMembersToNode"), type);
    } catch (JsonSyntaxException e) {
        throw new TencentCloudSDKException(e.getMessage());
    }
    return rsp.response;
}
 
Example #14
Source File: MariadbClient.java    From tencentcloud-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 *本接口(DescribeFlow)用于查询流程状态。
 * @param req DescribeFlowRequest
 * @return DescribeFlowResponse
 * @throws TencentCloudSDKException
 */
public DescribeFlowResponse DescribeFlow(DescribeFlowRequest req) throws TencentCloudSDKException{
    JsonResponseModel<DescribeFlowResponse> rsp = null;
    try {
            Type type = new TypeToken<JsonResponseModel<DescribeFlowResponse>>() {
            }.getType();
            rsp  = gson.fromJson(this.internalRequest(req, "DescribeFlow"), type);
    } catch (JsonSyntaxException e) {
        throw new TencentCloudSDKException(e.getMessage());
    }
    return rsp.response;
}
 
Example #15
Source File: MpsClient.java    From tencentcloud-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 *该接口用于批量创建关键词样本,样本用于通过OCR、ASR技术,进行内容审核、内容识别等视频处理。
 * @param req CreateWordSamplesRequest
 * @return CreateWordSamplesResponse
 * @throws TencentCloudSDKException
 */
public CreateWordSamplesResponse CreateWordSamples(CreateWordSamplesRequest req) throws TencentCloudSDKException{
    JsonResponseModel<CreateWordSamplesResponse> rsp = null;
    try {
            Type type = new TypeToken<JsonResponseModel<CreateWordSamplesResponse>>() {
            }.getType();
            rsp  = gson.fromJson(this.internalRequest(req, "CreateWordSamples"), type);
    } catch (JsonSyntaxException e) {
        throw new TencentCloudSDKException(e.getMessage());
    }
    return rsp.response;
}
 
Example #16
Source File: CvmClient.java    From tencentcloud-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
     *本接口 (AssociateSecurityGroups) 用于绑定安全组到指定实例。
* 实例操作结果可以通过调用 [DescribeInstances](https://cloud.tencent.com/document/api/213/15728#.E7.A4.BA.E4.BE.8B3-.E6.9F.A5.E8.AF.A2.E5.AE.9E.E4.BE.8B.E7.9A.84.E6.9C.80.E6.96.B0.E6.93.8D.E4.BD.9C.E6.83.85.E5.86.B5) 接口查询,如果实例的最新操作状态(LatestOperationState)为“SUCCESS”,则代表操作成功。
     * @param req AssociateSecurityGroupsRequest
     * @return AssociateSecurityGroupsResponse
     * @throws TencentCloudSDKException
     */
    public AssociateSecurityGroupsResponse AssociateSecurityGroups(AssociateSecurityGroupsRequest req) throws TencentCloudSDKException{
        JsonResponseModel<AssociateSecurityGroupsResponse> rsp = null;
        try {
                Type type = new TypeToken<JsonResponseModel<AssociateSecurityGroupsResponse>>() {
                }.getType();
                rsp  = gson.fromJson(this.internalRequest(req, "AssociateSecurityGroups"), type);
        } catch (JsonSyntaxException e) {
            throw new TencentCloudSDKException(e.getMessage());
        }
        return rsp.response;
    }
 
Example #17
Source File: TkeClient.java    From tencentcloud-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 *为已经存在的集群创建伸缩组
 * @param req CreateClusterAsGroupRequest
 * @return CreateClusterAsGroupResponse
 * @throws TencentCloudSDKException
 */
public CreateClusterAsGroupResponse CreateClusterAsGroup(CreateClusterAsGroupRequest req) throws TencentCloudSDKException{
    JsonResponseModel<CreateClusterAsGroupResponse> rsp = null;
    try {
            Type type = new TypeToken<JsonResponseModel<CreateClusterAsGroupResponse>>() {
            }.getType();
            rsp  = gson.fromJson(this.internalRequest(req, "CreateClusterAsGroup"), type);
    } catch (JsonSyntaxException e) {
        throw new TencentCloudSDKException(e.getMessage());
    }
    return rsp.response;
}
 
Example #18
Source File: PrepareRenameResponseAdapter.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
	Predicate<JsonElement> leftChecker = new PropertyChecker("start");
	Predicate<JsonElement> rightChecker = new PropertyChecker("range");
	return (TypeAdapter<T>) new EitherTypeAdapter<>(gson, ELEMENT_TYPE, leftChecker, rightChecker);
}
 
Example #19
Source File: KmsClient.java    From tencentcloud-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
     *用于导入密钥材料。只有类型为EXTERNAL 的CMK 才可以导入,导入的密钥材料使用 GetParametersForImport 获取的密钥进行加密。可以为指定的 CMK 重新导入密钥材料,并重新指定过期时间,但必须导入相同的密钥材料。CMK 密钥材料导入后不可以更换密钥材料。导入的密钥材料过期或者被删除后,指定的CMK将无法使用,需要再次导入相同的密钥材料才能正常使用。CMK是独立的,同样的密钥材料可导入不同的 CMK 中,但使用其中一个 CMK 加密的数据无法使用另一个 CMK解密。
只有Enabled 和 PendingImport状态的CMK可以导入密钥材料。
     * @param req ImportKeyMaterialRequest
     * @return ImportKeyMaterialResponse
     * @throws TencentCloudSDKException
     */
    public ImportKeyMaterialResponse ImportKeyMaterial(ImportKeyMaterialRequest req) throws TencentCloudSDKException{
        JsonResponseModel<ImportKeyMaterialResponse> rsp = null;
        try {
                Type type = new TypeToken<JsonResponseModel<ImportKeyMaterialResponse>>() {
                }.getType();
                rsp  = gson.fromJson(this.internalRequest(req, "ImportKeyMaterial"), type);
        } catch (JsonSyntaxException e) {
            throw new TencentCloudSDKException(e.getMessage());
        }
        return rsp.response;
    }
 
Example #20
Source File: VersionsApi.java    From nifi-swagger-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the Update Request with the given ID. Once an Update Request has been created by performing a POST to /versions/update-requests/process-groups/{id}, that request can subsequently be retrieved via this endpoint, and the request that is fetched will contain the updated state, such as percent complete, the current state of the request, and any failures. (asynchronously)
 * Note: This endpoint is subject to change as NiFi and it&#39;s REST API evolve.
 * @param id The ID of the Update Request (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 getUpdateRequestAsync(String id, final ApiCallback<VersionedFlowUpdateRequestEntity> 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 = getUpdateRequestValidateBeforeCall(id, progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<VersionedFlowUpdateRequestEntity>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
 
Example #21
Source File: PageClient.java    From domo-java-sdk with MIT License 5 votes vote down vote up
/**
 *  See <a href="https://developer.domo.com/docs/domo-apis/pages#API%20-%20List%20Pages">List Pages</a> Api Docs
 *
 * @param limit number of users to fetch
 * @param offset page offset of user result
 * @return List of <code>PageSummary</code>s
 */
public List<PageSummary> list(int limit, int offset) {
    HttpUrl url = urlBuilder.fromPathSegments(PAGES_URL)
            .addQueryParameter("limit", Integer.toString(limit))
            .addQueryParameter("offset", Integer.toString(offset))
            .build();

    return transport.getJson(url, new TypeToken<List<PageSummary>>(){}.getType());
}
 
Example #22
Source File: ClusterApi.java    From huaweicloud-cs-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * 查询路由列表 (asynchronously)
 * 
 * @param xProjectId  (required)
 * @param clusterId  (required)
 * @param peeringId  (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 getRoutesAsync(String xProjectId, Integer clusterId, String peeringId, final ApiCallback<GetRoutesResponse> 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 = getRoutesValidateBeforeCall(xProjectId, clusterId, peeringId, progressListener, progressRequestListener);
    Type localVarReturnType = new TypeToken<GetRoutesResponse>(){}.getType();
    apiClient.executeAsync(call, localVarReturnType, callback);
    return call;
}
 
Example #23
Source File: TypeAdapters.java    From framework with GNU Affero General Public License v3.0 5 votes vote down vote up
public static <TT> TypeAdapterFactory newFactory(
    final TypeToken<TT> type, final TypeAdapter<TT> typeAdapter) {
  return new TypeAdapterFactory() {
    @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
      return typeToken.equals(type) ? (TypeAdapter<T>) typeAdapter : null;
    }
  };
}
 
Example #24
Source File: JsonUtil.java    From UltimateAndroid with Apache License 2.0 5 votes vote down vote up
public static ArrayList getArrayListMapFromJson(String jsonString) {
    JsonParser jsonParser = new JsonParser();
    Gson gson = new Gson();
    JsonElement jsonElement = jsonParser.parse(jsonString);
    Logs.d(jsonElement.isJsonArray() + "   " + jsonElement.isJsonObject());
    ArrayList<HashMap<String, Object>> arrayList = new ArrayList<HashMap<String, Object>>();
    if (jsonElement.isJsonObject()) {
        arrayList.add(gson.fromJson(jsonElement, HashMap.class));
    } else if (jsonElement.isJsonArray()) {
        arrayList = getListFromJson(jsonString, new TypeToken<ArrayList<HashMap<String, Object>>>() {
        });
    }
    return arrayList;
}
 
Example #25
Source File: YunjingClient.java    From tencentcloud-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 *新增或修改本地提权规则
 * @param req EditPrivilegeRuleRequest
 * @return EditPrivilegeRuleResponse
 * @throws TencentCloudSDKException
 */
public EditPrivilegeRuleResponse EditPrivilegeRule(EditPrivilegeRuleRequest req) throws TencentCloudSDKException{
    JsonResponseModel<EditPrivilegeRuleResponse> rsp = null;
    try {
            Type type = new TypeToken<JsonResponseModel<EditPrivilegeRuleResponse>>() {
            }.getType();
            rsp  = gson.fromJson(this.internalRequest(req, "EditPrivilegeRule"), type);
    } catch (JsonSyntaxException e) {
        throw new TencentCloudSDKException(e.getMessage());
    }
    return rsp.response;
}
 
Example #26
Source File: MapTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testMapSerialization() {
  Map<String, Integer> map = new LinkedHashMap<String, Integer>();
  map.put("a", 1);
  map.put("b", 2);
  Type typeOfMap = new TypeToken<Map<String, Integer>>() {}.getType();
  String json = gson.toJson(map, typeOfMap);
  assertTrue(json.contains("\"a\":1"));
  assertTrue(json.contains("\"b\":2"));
}
 
Example #27
Source File: YoumallClient.java    From tencentcloud-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 *返回当前门店最新网络状态数据
 * @param req DescribeNetworkInfoRequest
 * @return DescribeNetworkInfoResponse
 * @throws TencentCloudSDKException
 */
public DescribeNetworkInfoResponse DescribeNetworkInfo(DescribeNetworkInfoRequest req) throws TencentCloudSDKException{
    JsonResponseModel<DescribeNetworkInfoResponse> rsp = null;
    try {
            Type type = new TypeToken<JsonResponseModel<DescribeNetworkInfoResponse>>() {
            }.getType();
            rsp  = gson.fromJson(this.internalRequest(req, "DescribeNetworkInfo"), type);
    } catch (JsonSyntaxException e) {
        throw new TencentCloudSDKException(e.getMessage());
    }
    return rsp.response;
}
 
Example #28
Source File: TkeClient.java    From tencentcloud-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 *创建托管集群外网访问端口(老的方式,仅支持托管集群外网端口)
 * @param req CreateClusterEndpointVipRequest
 * @return CreateClusterEndpointVipResponse
 * @throws TencentCloudSDKException
 */
public CreateClusterEndpointVipResponse CreateClusterEndpointVip(CreateClusterEndpointVipRequest req) throws TencentCloudSDKException{
    JsonResponseModel<CreateClusterEndpointVipResponse> rsp = null;
    try {
            Type type = new TypeToken<JsonResponseModel<CreateClusterEndpointVipResponse>>() {
            }.getType();
            rsp  = gson.fromJson(this.internalRequest(req, "CreateClusterEndpointVip"), type);
    } catch (JsonSyntaxException e) {
        throw new TencentCloudSDKException(e.getMessage());
    }
    return rsp.response;
}
 
Example #29
Source File: GsonUtil.java    From AndroidMagnetSearch with Apache License 2.0 5 votes vote down vote up
public static <T> T fromJson(String jsonText, TypeToken<T> token) {
    try {
        return gson.fromJson(jsonText, token.getType());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #30
Source File: MessageTypeAdapter.java    From lsp4j with Eclipse Public License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
	if (!Message.class.isAssignableFrom(typeToken.getRawType()))
		return null;
	return (TypeAdapter<T>) new MessageTypeAdapter(handler, gson);
}