本文整理匯總了Java中com.google.gson.JsonSyntaxException類的典型用法代碼示例。如果您正苦於以下問題:Java JsonSyntaxException類的具體用法?Java JsonSyntaxException怎麽用?Java JsonSyntaxException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
JsonSyntaxException類屬於com.google.gson包,在下文中一共展示了JsonSyntaxException類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: deserialize
import com.google.gson.JsonSyntaxException; //導入依賴的package包/類
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_);
}
示例2: deserialize
import com.google.gson.JsonSyntaxException; //導入依賴的package包/類
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);
}
}
示例3: getDeploymentEvents
import com.google.gson.JsonSyntaxException; //導入依賴的package包/類
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;
}
示例4: getGridOfWeek
import com.google.gson.JsonSyntaxException; //導入依賴的package包/類
/**
* Получение недельной таблици с данными для предварительной записи.
*
* @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();
}
示例5: parse
import com.google.gson.JsonSyntaxException; //導入依賴的package包/類
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);
}
}
示例6: readGeneric
import com.google.gson.JsonSyntaxException; //導入依賴的package包/類
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;
}
示例7: getUsers
import com.google.gson.JsonSyntaxException; //導入依賴的package包/類
/**
* Получение описания всех юзеров для выбора себя.
*
* @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();
}
示例8: read
import com.google.gson.JsonSyntaxException; //導入依賴的package包/類
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);
}
}
示例9: listBundle
import com.google.gson.JsonSyntaxException; //導入依賴的package包/類
/**
* 解析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;
}
示例10: checkJsonStatusResponse
import com.google.gson.JsonSyntaxException; //導入依賴的package包/類
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);
}
});
}
示例11: processResponse
import com.google.gson.JsonSyntaxException; //導入依賴的package包/類
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);
}
}
示例12: standAndCheckAdvance
import com.google.gson.JsonSyntaxException; //導入依賴的package包/類
/**
* Предварительная запись в очередь.
*
* @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, params);
} catch (QException e) {// вывод исключений
throw new ClientException(Locales.locMes("command_error2"), 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;
}
示例13: deserializeResponseBody
import com.google.gson.JsonSyntaxException; //導入依賴的package包/類
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);
}
}
示例14: deleteServiseFire
import com.google.gson.JsonSyntaxException; //導入依賴的package包/類
/**
* Удалить сервис из списока обслуживаемых юзером использую параметры. Используется при
* добавлении на горячую.
*
* @param netProperty параметры соединения с пунктом регистрации
* @return содержить строковое сообщение о результате.
*/
public static String deleteServiseFire(INetProperty netProperty, long serviceId, 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();
}
示例15: mapChartData
import com.google.gson.JsonSyntaxException; //導入依賴的package包/類
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;
}