项目:Backmemed
文件:LootConditionManager.java
public LootCondition deserialize(JsonElement p_deserialize_1_,Type p_deserialize_2_,JsonDeserializationContext p_deserialize_3_) throws JsonParseException
{
JsonObject jsonobject = JsonUtils.getJsonObject(p_deserialize_1_,"condition");
ResourceLocation resourcelocation = new ResourceLocation(JsonUtils.getString(jsonobject,"condition"));
LootCondition.Serializer<?> serializer;
try
{
serializer = LootConditionManager.getSerializerForName(resourcelocation);
}
catch (IllegalArgumentException var8)
{
throw new JsonSyntaxException("Unknown condition \'" + resourcelocation + "\'");
}
return serializer.deserialize(jsonobject,p_deserialize_3_);
}
项目:CustomWorldGen
文件:SetAttributes.java
public SetAttributes deserialize(JsonObject object,JsonDeserializationContext deserializationContext,LootCondition[] conditionsIn)
{
JsonArray jsonarray = JsonUtils.getJsonArray(object,"modifiers");
SetAttributes.Modifier[] asetattributes$modifier = new SetAttributes.Modifier[jsonarray.size()];
int i = 0;
for (JsonElement jsonelement : jsonarray)
{
asetattributes$modifier[i++] = SetAttributes.Modifier.deserialize(JsonUtils.getJsonObject(jsonelement,"modifier"),deserializationContext);
}
if (asetattributes$modifier.length == 0)
{
throw new JsonSyntaxException("Invalid attribute modifiers array; cannot be empty");
}
else
{
return new SetAttributes(conditionsIn,asetattributes$modifier);
}
}
项目:oneops
文件:MessagePublisherTest.java
private List<CMSEvent> getDeploymentEvents() {
List<CMSEvent> events = new ArrayList<>();
try {
InputStream is = this.getClass().getClassLoader().getResourceAsStream("deployment-events.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = reader.readLine();
while (line != null) {
CMSEvent event = new CMSEvent();
event.addHeaders("sourceId","546589");
event.addHeaders("action","update");
event.addHeaders("source","deployment");
event.addHeaders("clazzName","Deployment");
CmsDeployment deployment = gson.fromJson(line,CmsDeployment.class);
event.setPayload(deployment);
events.add(event);
line = reader.readLine();
}
} catch (JsonSyntaxException | IOException e) {
e.printStackTrace();
}
return events;
}
项目:sbc-qsystem
文件:NetCommander.java
/**
* Получение недельной таблици с данными для предварительной записи.
*
* @param netProperty netProperty параметры соединения с сервером.
* @param serviceId услуга,в которую пытаемся встать.
* @param date первый день недели за которую нужны данные.
* @param advancedCustomer ID авторизованного кастомера
* @return класс с параметрами и списком времен
*/
public static RpcGetGridOfWeek.GridAndParams getGridOfWeek(INetProperty netProperty,long serviceId,Date date,long advancedCustomer) {
QLog.l().logger().info("Получить таблицу");
// загрузим ответ
final CmdParams params = new CmdParams();
params.serviceId = serviceId;
params.date = date.getTime();
params.customerId = advancedCustomer;
final String res;
try {
res = send(netProperty,Uses.TASK_GET_GRID_OF_WEEK,params);
} catch (QException e) {// вывод исключений
throw new ClientException(Locales.locMes("command_error2"),e);
}
final Gson gson = GsonPool.getInstance().borrowGson();
final RpcGetGridOfWeek rpc;
try {
rpc = gson.fromJson(res,RpcGetGridOfWeek.class);
} catch (JsonSyntaxException ex) {
throw new ClientException(Locales.locMes("bad_response") + "\n" + ex.toString());
} finally {
GsonPool.getInstance().returnGson(gson);
}
return rpc.getResult();
}
项目:letv
文件:Streams.java
public static JsonElement parse(JsonReader reader) throws JsonParseException {
boolean isEmpty = true;
try {
reader.peek();
isEmpty = false;
return (JsonElement) TypeAdapters.JSON_ELEMENT.read(reader);
} catch (Throwable e) {
if (isEmpty) {
return JsonNull.INSTANCE;
}
throw new JsonIOException(e);
} catch (Throwable e2) {
throw new JsonSyntaxException(e2);
} catch (Throwable e22) {
throw new JsonIOException(e22);
} catch (Throwable e222) {
throw new JsonSyntaxException(e222);
}
}
项目:ZentrelaRPG
文件:GenericNPCManager.java
public static int readGeneric(File f) {
int count = 0;
Gson gson = new GsonBuilder().setPrettyPrinting().registerTypeAdapter(Location.class,new LocationAdapter()).create();
try (FileReader reader = new FileReader(f)) {
GenericNPC[] vils = gson.fromJson(reader,GenericNPC[].class);
for (GenericNPC gv : vils) {
if (gv == null)
continue;
NPCManager.register(gv);
genericVillagers.add(gv);
}
count += vils.length;
} catch (JsonSyntaxException | JsonIOException | IOException e) {
System.err.println("Error reading NPC in " + f.getName() + ".");
e.printStackTrace();
}
return count;
}
项目:sbc-qsystem
文件:NetCommander.java
/**
* Получение описания всех юзеров для выбора себя.
*
* @param netProperty параметры соединения с сервером
* @return XML-ответ все юзеры системы
*/
public static LinkedList<QUser> getUsers(INetProperty netProperty) {
QLog.l().logger().info("Получение описания всех юзеров для выбора себя.");
// загрузим ответ
String res = null;
try {
res = send(netProperty,Uses.TASK_GET_USERS,null);
} catch (QException e) {// вывод исключений
Uses.closeSplash();
throw new ClientException(Locales.locMes("command_error2"),e);
} finally {
if (res == null || res.isEmpty()) {
System.exit(1);
}
}
final Gson gson = GsonPool.getInstance().borrowGson();
final RpcGetUsersList rpc;
try {
rpc = gson.fromJson(res,RpcGetUsersList.class);
} catch (JsonSyntaxException ex) {
throw new ClientException(Locales.locMes("bad_response") + "\n" + ex.toString());
} finally {
GsonPool.getInstance().returnGson(gson);
}
return rpc.getResult();
}
项目:letv
文件:ReflectiveTypeAdapterFactory.java
public T read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
return null;
}
T instance = this.constructor.construct();
try {
in.beginObject();
while (in.hasNext()) {
BoundField field = (BoundField) this.boundFields.get(in.nextName());
if (field == null || !field.deserialized) {
in.skipValue();
} else {
field.read(in,instance);
}
}
in.endObject();
return instance;
} catch (Throwable e) {
throw new JsonSyntaxException(e);
} catch (IllegalAccessException e2) {
throw new AssertionError(e2);
}
}
项目:Gather-Platform
文件:ResultBundleResolver.java
/**
* 解析ResultListBundle
*
* @param json 服务器返回的json数据
* @param <T>
* @return
*/
public <T> ResultListBundle<T> listBundle(String json,Class<T> classOfT) {
ResultListBundle<T> resultBundle = null;
try {
Type objectType = new ParameterizedType() {
public Type getRawType() {
return ResultListBundle.class;
}
public Type[] getActualTypeArguments() {
return new Type[]{classOfT};
}
public Type getOwnerType() {
return null;
}
};
resultBundle = gson.fromJson(json,objectType);
} catch (JsonSyntaxException e) {
LOG.error("无法解析的返回值信息:" + json);
e.printStackTrace();
}
validate(resultBundle);
return resultBundle;
}
项目:RunHDU
文件:BaseModel.java
private static void checkJsonStatusResponse(Response response,BaseCallback callback) throws IOException {
String jsonStr = response.body().string();
Log.d(TAG,"checkJsonStatusResponse: " + jsonStr);
mHandler.post(() -> {
Status status = null;
try {
status = new Gson().fromJson(jsonStr,Status.class);
if (status.getResult()) {
callback.onSuccess();
} else {
callback.onFailure(status.getMessage());
}
} catch (JsonSyntaxException e) {
e.printStackTrace();
callback.onFailure(RETURN_DATA_ERROR);
}
});
}
项目:Babler
文件:Client.java
private <T> T processResponse(Class<T> responseClass,String body)
throws APIError {
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
if (body.contains("\"error\":")) {
ErrorResponse errorResponse = gson.fromJson(body,ErrorResponse.class);
ErrorData error = errorResponse.error;
throw new APIError(error.message,error.code);
}
try {
return gson.fromJson(body,responseClass);
} catch (JsonSyntaxException e) {
throw new APIError("Server error. Invalid response format.",9999);
}
}
项目:sbc-qsystem
文件:NetCommander.java
/**
* Предварительная запись в очередь.
*
* @param netProperty netProperty параметры соединения с сервером.
* @param advanceID идентификатор предварительно записанного.
* @return XML-ответ.
*/
public static RpcStandInService standAndCheckAdvance(INetProperty netProperty,Long advanceID) {
QLog.l().logger().info("Постановка предварительно записанных в очередь.");
// загрузим ответ
final CmdParams params = new CmdParams();
params.customerId = advanceID;
final String res;
try {
res = send(netProperty,Uses.TASK_ADVANCE_CHECK_AND_STAND,e);
}
final Gson gson = GsonPool.getInstance().borrowGson();
final RpcStandInService rpc;
try {
rpc = gson.fromJson(res,RpcStandInService.class);
} catch (JsonSyntaxException ex) {
throw new ClientException(Locales.locMes("bad_response") + "\n" + ex.toString());
} finally {
GsonPool.getInstance().returnGson(gson);
}
return rpc;
}
项目:pcloud-sdk-java
文件:RealApiClient.java
private <T> T deserializeResponseBody(Response response,Class<? extends T> bodyType) throws IOException {
try {
if (!response.isSuccessful()) {
throw new APIHttpException(response.code(),response.message());
}
JsonReader reader = new JsonReader(new BufferedReader(new InputStreamReader(response.body().byteStream())));
try {
return gson.fromJson(reader,bodyType);
} catch (JsonSyntaxException e) {
throw new IOException("Malformed JSON response.",e);
} finally {
closeQuietly(reader);
}
} finally {
closeQuietly(response);
}
}
项目:sbc-qsystem
文件:NetCommander.java
/**
* Удалить сервис из списока обслуживаемых юзером использую параметры. Используется при
* добавлении на горячую.
*
* @param netProperty параметры соединения с пунктом регистрации
* @return содержить строковое сообщение о результате.
*/
public static String deleteServiseFire(INetProperty netProperty,long userId) {
QLog.l().logger().info("Удаление услуги пользователю на горячую.");
// загрузим ответ
final CmdParams params = new CmdParams();
params.userId = userId;
params.serviceId = serviceId;
final String res;
try {
res = send(netProperty,Uses.TASK_DELETE_SERVICE_FIRE,params);
} catch (QException e) {
throw new ClientException(Locales.locMes("bad_response") + "\n" + e.toString());
}
final Gson gson = GsonPool.getInstance().borrowGson();
final RpcGetSrt rpc;
try {
rpc = gson.fromJson(res,RpcGetSrt.class);
} catch (JsonSyntaxException ex) {
throw new ClientException(Locales.locMes("bad_response") + "\n" + ex.toString());
} finally {
GsonPool.getInstance().returnGson(gson);
}
return rpc.getResult();
}
项目:poloniex-api-java
文件:PoloniexDataMapper.java
public List<PoloniexChartData> mapChartData(String chartDataResult) {
if (INVALID_CHART_DATA_DATE_RANGE_RESULT.equals(chartDataResult) || INVALID_CHART_DATA_CURRENCY_PAIR_RESULT.equals(chartDataResult)) {
return Collections.EMPTY_LIST;
}
List<PoloniexChartData> results;
try {
PoloniexChartData[] chartDataResults = gson.fromJson(chartDataResult,PoloniexChartData[].class);
results = Arrays.asList(chartDataResults);
} catch (JsonSyntaxException | DateTimeParseException ex) {
LogManager.getLogger().error("Exception mapping chart data {} - {}",chartDataResult,ex.getMessage());
results = Collections.EMPTY_LIST;
}
return results;
}
项目:CustomWorldGen
文件:JsonUtils.java
/**
* Gets the float value of the field on the JsonObject with the given name.
*/
public static float getFloat(JsonObject json,String memberName)
{
if (json.has(memberName))
{
/**
* Gets the float value of the given JsonElement. Expects the second parameter to be the name of the
* element's field if an error message needs to be thrown.
*/
return getFloat(json.get(memberName),memberName);
}
else
{
throw new JsonSyntaxException("Missing " + memberName + ",expected to find a Float");
}
}
项目:Repository-ArchComponents
文件:PrettyHttpLogger.java
@Override
public void log(@NonNull String message) {
if (!message.startsWith("{") && !message.startsWith("[")) {
largeLog(TAG,message);
return;
}
try {
String prettyPrintJson = new GsonBuilder()
.setPrettyPrinting()
.create()
.toJson(new JsonParser().parse(message));
largeLog(TAG,prettyPrintJson);
} catch (JsonSyntaxException exception) {
largeLog(TAG,"html header parse failed");
exception.printStackTrace();
largeLog(TAG,message);
}
}
项目:catalog-api-demo
文件:Main.java
/**
* Attempts to log {@link Error}s from an {@link ApiException},or rethrows if the response body
* cannot be parsed.
*/
private void handleApiException(ApiException apiException) {
try {
// If the response includes a body,it means that he server returned some error message.
ErrorResponse response =
GsonProvider.gson().fromJson(apiException.getResponseBody(),ErrorResponse.class);
// If we found errors in the response body,log them. Otherwise,rethrow.
if (!checkAndLogErrors(response.errors,logger)) {
throw new RuntimeException(apiException);
}
} catch (JsonSyntaxException e) {
// If the error message isn't in JSON format,rethrow the error.
throw new RuntimeException(apiException);
}
}
项目:Slide-RSS
文件:HttpUtil.java
/**
* Gets a JsonObject by calling apiUrl and parsing the JSON response String. This method accepts
* a Map that can contain custom headers to include in the request.
*
* @param client The OkHTTP client to use to make the request
* @param gson The GSON instance to use to parse the response String
* @param apiUrl The URL to call to get the response from
* @param headersMap The headers to include in the request. Can be null to not add any headers
* @return A JsonObject representation of the API response,null when there was an error or
* Exception thrown by the HTTP call
*/
public static JsonObject getJsonObject(final OkHttpClient client,final Gson gson,final String apiUrl,@Nullable final Map<String,String> headersMap) {
if (client == null || gson == null || TextUtils.isEmpty(apiUrl)) return null;
Request.Builder builder = new Request.Builder().url(apiUrl);
if (headersMap != null && headersMap.size() > 0) {
// Add headers to the request if headers are available
for (Map.Entry<String,String> entry : headersMap.entrySet()) {
builder.addHeader(entry.getKey(),entry.getValue());
}
}
Request request = builder.build();
try {
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
ResponseBody responseBody = response.body();
String json = responseBody.string();
responseBody.close();
return gson.fromJson(json,JsonObject.class);
} catch (JsonSyntaxException | IOException e) {
LogUtil.e(e,"Error " + apiUrl);
}
return null;
}
项目:Enjin-Coin-Java-SDK
文件:JsonUtils.java
/**
* Method to convert a json string to an object.
*
* @param gson gson object
* @param jsonString json to convert to an object
* @param responseClass class type to convert to
* @return An object representing the json in the fileReader
*/
public static Object convertJsonToObject(final Gson gson,final String jsonString,final Class<?> responseClass) {
Object responseObject = null;
if (gson == null || StringUtils.isEmpty(jsonString) || ObjectUtils.isNull(responseClass)) {
LOGGER.warning("gson passed in is null or jsonString passed in is null or empty or the responseClass is null");
return responseObject;
}
// JSON from file to Object
try {
LOGGER.fine(String.format("jsonString:%s",jsonString));
responseObject = gson.fromJson(jsonString,responseClass);
} catch (JsonSyntaxException e) {
LOGGER.warning(String.format("A JsonSyntaxException has occured. Exception: %s",StringUtils.exceptionToString(e)));
}
return responseObject;
}
项目:Backmemed
文件:EntityRenderer.java
public void loadShader(ResourceLocation resourceLocationIn)
{
if (OpenGlHelper.isFramebufferEnabled())
{
try
{
this.theShaderGroup = new ShaderGroup(this.mc.getTextureManager(),this.resourceManager,this.mc.getFramebuffer(),resourceLocationIn);
this.theShaderGroup.createBindFramebuffers(this.mc.displayWidth,this.mc.displayHeight);
this.useShader = true;
}
catch (IOException ioexception)
{
LOGGER.warn("Failed to load shader: {}",new Object[] {resourceLocationIn,ioexception});
this.shaderIndex = SHADER_COUNT;
this.useShader = false;
}
catch (JsonSyntaxException jsonsyntaxexception)
{
LOGGER.warn("Failed to load shader: {}",jsonsyntaxexception});
this.shaderIndex = SHADER_COUNT;
this.useShader = false;
}
}
}
项目:Backmemed
文件:EnchantRandomly.java
public EnchantRandomly deserialize(JsonObject object,LootCondition[] conditionsIn)
{
List<Enchantment> list = Lists.<Enchantment>newArrayList();
if (object.has("enchantments"))
{
for (JsonElement jsonelement : JsonUtils.getJsonArray(object,"enchantments"))
{
String s = JsonUtils.getString(jsonelement,"enchantment");
Enchantment enchantment = (Enchantment)Enchantment.REGISTRY.getObject(new ResourceLocation(s));
if (enchantment == null)
{
throw new JsonSyntaxException("Unknown enchantment \'" + s + "\'");
}
list.add(enchantment);
}
}
return new EnchantRandomly(conditionsIn,list);
}
项目:sbc-qsystem
文件:NetCommander.java
/**
* Добавить сервис в список обслуживаемых юзером использую параметры. Используется при
* добавлении на горячую.
*
* @param netProperty параметры соединения с пунктом регистрации
* @return содержить строковое сообщение о результате.
*/
public static String setServiseFire(INetProperty netProperty,long userId,int coeff) {
QLog.l().logger().info("Привязка услуги пользователю на горячую.");
// загрузим ответ
final CmdParams params = new CmdParams();
params.userId = userId;
params.serviceId = serviceId;
params.coeff = coeff;
final String res;
try {
res = send(netProperty,Uses.TASK_SET_SERVICE_FIRE,RpcGetSrt.class);
} catch (JsonSyntaxException ex) {
throw new ClientException(Locales.locMes("bad_response") + "\n" + ex.toString());
} finally {
GsonPool.getInstance().returnGson(gson);
}
return rpc.getResult();
}
项目:CustomWorldGen
文件:EnchantRandomly.java
public EnchantRandomly deserialize(JsonObject object,LootCondition[] conditionsIn)
{
List<Enchantment> list = null;
if (object.has("enchantments"))
{
list = Lists.<Enchantment>newArrayList();
for (JsonElement jsonelement : JsonUtils.getJsonArray(object,list);
}
项目:matrix
文件:GsonHelper.java
/**
* json字符串转为T的List对象
* @param json
* @param clazz
* @param <T>
* @return
*/
public static <T> ArrayList<T> formatList(String json,Class<T> clazz) {
Type type = new TypeToken<ArrayList<JsonObject>>() {
}.getType();
ArrayList<T> arrayList = null;
try {
ArrayList<JsonObject> jsonObjects = sGson.fromJson(json,type);
if (jsonObjects != null && jsonObjects.size() > 0) {
arrayList = new ArrayList<>();
for (JsonObject jsonObject : jsonObjects) {
arrayList.add(sGson.fromJson(jsonObject,clazz));
}
}
} catch (JsonSyntaxException e) {
return null;
}
return arrayList;
}
项目:webauthndemo
文件:AuthenticatorAssertionResponse.java
/**
* @param data
* @throws ResponseException
*/
public AuthenticatorAssertionResponse(JsonElement data) throws ResponseException {
Gson gson = new Gson();
try {
AssertionResponseJson parsedObject = gson.fromJson(data,AssertionResponseJson.class);
clientDataBytes = BaseEncoding.base64().decode(parsedObject.clientDataJSON);
clientData = gson.fromJson(new String(clientDataBytes),CollectedClientData.class);
authDataBytes = BaseEncoding.base64().decode(parsedObject.authenticatorData);
authData =
AuthenticatorData.decode(authDataBytes);
signature = BaseEncoding.base64().decode(parsedObject.signature);
userHandle = BaseEncoding.base64().decode(parsedObject.userHandle);
} catch (JsonSyntaxException e) {
throw new ResponseException("Response format incorrect");
}
}
项目:CompositeGear
文件:IC2IngredientFactory.java
@Override
public Ingredient parse(JsonContext context,JsonObject json)
{
String name = JsonUtils.getString(json,"name");
ItemStack stack = null;
// If item with variant.
if (name.contains("#")) {
String[] parts = name.split("#");
stack = IC2Items.getItem(parts[0],parts[1]);
} else {
stack = IC2Items.getItem(name);
}
if (stack == null)
throw new JsonSyntaxException("IC2 item with name " + name + " could not be found");
return Ingredient.fromStacks(stack);
}
项目:bench
文件:Json.java
public static boolean isValid(String jsonToCheck) {
try {
gson.fromJson(jsonToCheck,Object.class);
return true;
} catch (JsonSyntaxException e) {
log.error("Invalid syntax for {}",jsonToCheck,e);
return false;
}
}
项目:BaseClient
文件:JsonUtils.java
/**
* Gets the string value of the field on the JsonObject with the given name.
*/
public static String getString(JsonObject p_151200_0_,String p_151200_1_)
{
if (p_151200_0_.has(p_151200_1_))
{
return getString(p_151200_0_.get(p_151200_1_),p_151200_1_);
}
else
{
throw new JsonSyntaxException("Missing " + p_151200_1_ + ",expected to find a string");
}
}
项目:PhotoScript
文件:IOUtils.java
public static <T> T getObjectData(String jsonString,Class<T> type) {
T t = null;
try {
Gson gson = new Gson();
t = gson.fromJson(jsonString,type);
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
return t;
}
项目:GitHub
文件:GsonHelper.java
/**
* 将json数据转化为实体数据
* @param jsonData json字符串
* @param entityClass 类型
* @return 实体
*/
public static <T> T convertEntity(String jsonData,Class<T> entityClass) {
T entity = null;
try {
entity = sGson.fromJson(jsonData.toString(),entityClass);
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
return entity;
}
项目:GitHub
文件:ApiSubcriber.java
@Override
public void onError(Throwable e) {
NetError error = null;
if (e != null) {
if (!(e instanceof NetError)) {
if (e instanceof UnknownHostException) {
error = new NetError(e,NetError.NoConnectError);
} else if (e instanceof JSONException
|| e instanceof JsonParseException
|| e instanceof JsonSyntaxException) {
error = new NetError(e,NetError.ParseError);
} else {
error = new NetError(e,NetError.OtherError);
}
} else {
error = (NetError) e;
}
if (useCommonErrorHandler()
&& XApi.getCommonProvider() != null) {
if (XApi.getCommonProvider().handleError(error)) { //使用通用异常处理
return;
}
}
onFail(error);
}
}
项目:apollo-custom
文件:ConfigControllerTest.java
@Test(expected = JsonSyntaxException.class)
public void testTransformConfigurationToMapFailed() throws Exception {
String someInvalidConfiguration = "xxx";
Release someRelease = new Release();
someRelease.setConfigurations(someInvalidConfiguration);
configController.mergeReleaseConfigurations(Lists.newArrayList(someRelease));
}
项目:Backmemed
文件:RenderGlobal.java
/**
* Creates the entity outline shader to be stored in RenderGlobal.entityOutlineShader
*/
public void makeEntityOutlineShader()
{
if (OpenGlHelper.shadersSupported)
{
if (ShaderLinkHelper.getStaticShaderLinkHelper() == null)
{
ShaderLinkHelper.setNewStaticShaderLinkHelper();
}
ResourceLocation resourcelocation = new ResourceLocation("shaders/post/entity_outline.json");
try
{
this.entityOutlineShader = new ShaderGroup(this.mc.getTextureManager(),this.mc.getResourceManager(),resourcelocation);
this.entityOutlineShader.createBindFramebuffers(this.mc.displayWidth,this.mc.displayHeight);
this.entityOutlineFramebuffer = this.entityOutlineShader.getFramebufferRaw("final");
}
catch (IOException ioexception)
{
LOGGER.warn("Failed to load shader: {}",new Object[] {resourcelocation,ioexception});
this.entityOutlineShader = null;
this.entityOutlineFramebuffer = null;
}
catch (JsonSyntaxException jsonsyntaxexception)
{
LOGGER.warn("Failed to load shader: {}",jsonsyntaxexception});
this.entityOutlineShader = null;
this.entityOutlineFramebuffer = null;
}
}
else
{
this.entityOutlineShader = null;
this.entityOutlineFramebuffer = null;
}
}
项目:alphavantage4j
文件:DigitalCurrencyParser.java
@Override
public Data resolve(JsonObject rootObject) {
Type metaDataType = new TypeToken<Map<String,String>>() {
}.getType();
Type dataType = new TypeToken<Map<String,Map<String,String>>>() {
}.getType();
try {
Map<String,String> metaData = GSON.fromJson(rootObject.get("Meta Data"),metaDataType);
Map<String,String>> digitalCurrencyData = GSON.fromJson(rootObject.get(getDigitalCurrencyDataKey()),dataType);
return resolve(metaData,digitalCurrencyData);
} catch (JsonSyntaxException e) {
throw new AlphaVantageException("time series api change",e);
}
}
项目:Weather-Guru-MVP
文件:ErrorHandlerHelper.java
public Throwable getProperException(Throwable throwable) {
if (throwable instanceof HttpException) {
HttpException httpException = (HttpException) throwable;
Response response = httpException.response();
// try to parse the error
Converter<ResponseBody,DataResponseModel> converter =
retrofit.responseBodyConverter(DataResponseModel.class,new Annotation[0]);
DataResponseModel error = null;
try {
error = converter.convert(response.errorBody());
} catch (IOException | JsonSyntaxException e) {
e.printStackTrace();
}
if (error == null || error.getData() == null || error.getData().getError() == null) {
return getThrowable(response.message(),response.code(),throwable);
} else {
return new ParsedResponseException(error.getData().getError().get(0).getMsg());
}
} else if (throwable instanceof IOException) {
return new InternetConnectionException();
} else if (throwable instanceof NetworkErrorException) {
return new InternetConnectionException();
}
return throwable;
}
项目:openssp
文件:SSPBroker.java
public static BidResponse.Builder parse(final String result,final SSPAdapter adapter) {
RtbResponseLogProcessor.instance.setLogData(result,"bidresponse",adapter.getName());
try {
// TODO: define new responsetype
final BidResponse response = gson.fromJson(result,BidResponse.class);
return response.getBuilder();
} catch (final JsonIOException | JsonSyntaxException e) {
log.error(e.getMessage());
}
return null;
}
项目:GenericTools
文件:NBTReflectionUtil.java
public static <T> T getObject(ItemStack item,NBTCompound comp,String key,Class<T> type) {
String json = getString(item,comp,key);
if (json == null) {
return null;
}
try {
return deserializeJson(json,type);
} catch (JsonSyntaxException ex) {
ex.printStackTrace();
}
return null;
}
项目:scalable-task-scheduler
文件:TaskSchedulerClientImpl.java
@Override
public String deleteTask(String taskId,Boolean retryable) {
Task task = new Task(SchedulingType.ONE_TIME);
task.setTaskId(taskId);
log.info("Trying to connect to scheduling service to delete task...");
String url = HttpUtils.URLBuilder.newURL()
.withHttpMode(HttpMode.HTTP)
.withServerIp(taskSchedulerAddress)
.withURI(RestURIConstants.TASK_MANAGER_BASE_URI + RestURIConstants.TASK)
.build();
try {
log.debug("Accessing URL: {}",url);
return HttpUtils.processHttpRequest(url,GenericResponse.class,task,HttpMethod.DELETE).toString();
} catch (GenericException se) {
log.info("Task deletion request failed. Retry available?: {}",retryable);
if (retryable) {
log.info("Retry mechanism is being applied.");
Status status = producer.send(ServiceConstants.DELETE_TASK,task);
return status.toString();
}
log.error("Service Exception occurred. Could not delete task");
try {
ExceptionResponse exception = JsonUtils.fromJson(se.getErrMessage(),ExceptionResponse.class);
throw new ServiceException(exception.getCode(),exception.getMessage());
} catch (JsonSyntaxException jse) {
throw se;
}
}
}
项目:nest-spider
文件:ResultBundleResolver.java
public <T> ResultBundle<T> bundle(String json) {
ResultBundle<T> result = null;
try {
Type objType = new TypeToken<ResultBundle<T>>() {}.getType();
result = GSON.fromJson(json,objType);
} catch(JsonSyntaxException e) {
LOG.error("无法解析的返回值,由于 " + e.getLocalizedMessage());
}
check(result);
return result;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。