List of usage examples for com.google.gson JsonSyntaxException JsonSyntaxException
public JsonSyntaxException(Throwable cause)
From source file:LongDateTypeAdapter.java
License:Apache License
@Override public Date read(JsonReader in) throws IOException { switch (in.peek()) { case NULL:/*from w w w .j a v a 2 s. c o m*/ return null; case STRING: try { return new Date(Long.parseLong(in.nextString())); } catch (NumberFormatException e) { throw new JsonSyntaxException(e); } default: throw new JsonSyntaxException("invalid date" + in.getPath()); } }
From source file:abfab3d.shapejs.ShapeJSEvaluator.java
License:LGPL
private Scriptable mungeParam(Parameter param, String json) { Scriptable wrapped = null;//from w ww .j a va 2 s .c om if (DEBUG) printf("Munging: %s type: %s\n", param.getName(), param.getType()); try { switch (param.getType()) { case BOOLEAN: Boolean bv = gson.fromJson(json, Boolean.class); BooleanParameter bp = (BooleanParameter) param; bp.setValue(bv); wrapped = new ParameterJSWrapper(scope, bp); break; case DOUBLE: Double dv = gson.fromJson(json, Double.class); DoubleParameter dp = (DoubleParameter) param; dp.setValue(dv); wrapped = new ParameterJSWrapper(scope, dp); break; case INTEGER: Integer iv = gson.fromJson(json, Integer.class); IntParameter ip = (IntParameter) param; ip.setValue(iv); wrapped = new ParameterJSWrapper(scope, ip); break; case DOUBLE_LIST: List<Number> dlv = gson.fromJson(json, doubleListType); NativeArray dlna = new NativeArray(dlv.size()); int dllen = dlv.size(); for (int i = 0; i < dllen; i++) { Double num = null; Object nob = dlv.get(i); if (nob instanceof Double) num = (Double) nob; else num = ((Number) nob).doubleValue(); dlna.put(i, dlna, new ParameterJSWrapper(scope, new DoubleParameter(param.getName(), param.getDesc(), num))); } wrapped = dlna; break; case AXIS_ANGLE_4D: AxisAngle4d aa = null; String jsonVal = json.trim(); // Handle string value in both formats: // - double list [x,y,z,angle] // - axis angle {"x":1,"y":0,"z":0,"angle":0} if (jsonVal.startsWith("[")) { aa = new AxisAngle4d(); List<Number> aalv = gson.fromJson(jsonVal, doubleListType); int aalen = aalv.size(); if (aalen != 4) { throw new IllegalArgumentException( "Axis angle must be 4 values: " + param.getName() + " val: " + json); } Object nob = aalv.get(0); if (nob instanceof Double) aa.x = (Double) nob; else aa.x = ((Number) nob).doubleValue(); nob = aalv.get(1); if (nob instanceof Double) aa.y = (Double) nob; else aa.y = ((Number) nob).doubleValue(); nob = aalv.get(2); if (nob instanceof Double) aa.z = (Double) nob; else aa.z = ((Number) nob).doubleValue(); nob = aalv.get(3); if (nob instanceof Double) aa.angle = (Double) nob; else aa.angle = ((Number) nob).doubleValue(); } else if (jsonVal.startsWith("{")) { aa = (AxisAngle4d) gson.fromJson(jsonVal, axisAngle4DType); } wrapped = new ParameterJSWrapper(scope, new AxisAngle4dParameter(param.getName(), param.getDesc(), aa)); break; case STRING: String sv = null; try { // A regular string is invalid json, but gson parses it and returns a "null" string if (json.equals("")) { throw new JsonSyntaxException("Invalid json: " + json); } // json of string consisting of spaces also returns a "null" string String trimmed = json.trim(); if (trimmed.equals("")) { sv = json; } else { sv = gson.fromJson(json, String.class); } } catch (JsonSyntaxException jse) { sv = json; } StringParameter sp = (StringParameter) param; sp.setValue(sv); wrapped = new ParameterJSWrapper(scope, sp); break; case COLOR: String cv = null; try { cv = gson.fromJson(json, String.class); } catch (JsonSyntaxException jse) { cv = json; } if (cv == null) { cv = json; } ColorParameter cp = (ColorParameter) param; cp.setValue(Color.fromHEX(cv)); wrapped = new ParameterJSWrapper(scope, cp); break; case ENUM: String ev = null; try { ev = gson.fromJson(json, String.class); } catch (JsonSyntaxException jse) { ev = json; } EnumParameter ep = (EnumParameter) param; ep.setValue(ev); wrapped = new ParameterJSWrapper(scope, ep); break; case URI: // TODO: not JSON encoded decide if we want this String uv = null; if (json.charAt(0) == '"') { uv = gson.fromJson(json, String.class); } else { uv = json; } //uv = Utils.checkForValidShapewaysUri(uv); URIParameter up = (URIParameter) param; up.setValue(uv); wrapped = new ParameterJSWrapper(scope, up); break; case URI_LIST: String[] ulv = gson.fromJson(json, String[].class); NativeArray ulna = new NativeArray(ulv.length); int ullen = ulv.length; for (int i = 0; i < ullen; i++) { String st = ulv[i]; //st = Utils.checkForValidShapewaysUri(st); ulna.put(i, ulna, new ParameterJSWrapper(scope, new URIParameter(param.getName(), param.getDesc(), st))); } wrapped = ulna; break; case STRING_LIST: List<String> slv = gson.fromJson(json, stringListType); NativeArray slna = new NativeArray(slv.size()); int sllen = slv.size(); for (int i = 0; i < sllen; i++) { String st = slv.get(i); slna.put(i, slna, new ParameterJSWrapper(scope, new StringParameter(param.getName(), param.getDesc(), st))); slna.put(i, slna, new ParameterJSWrapper(scope, new StringParameter(param.getName(), param.getDesc(), st))); } wrapped = slna; break; case LOCATION: if (json == null || json.length() == 0 || json.equals("null") || json.equals("\"null\"")) return null; if (DEBUG) printf("Parsing location: json is: %s\n", json); Map<String, Object> map = gson.fromJson(json, Map.class); if (map == null) return null; Vector3d point = null; Vector3d normal = null; Object o = map.get("point"); if (o != null) { mungeToVector3d(o, v3d1); point = new Vector3d(v3d1); } o = map.get("normal"); if (o != null) { mungeToVector3d(o, v3d2); normal = new Vector3d(v3d2); } LocationParameter lp = (LocationParameter) param; if (point != null && normal != null) { Vector3d[] lpVal = { point, normal }; lp.setValue(lpVal); wrapped = (Scriptable) Context.javaToJS(lp, scope); } break; case USERDEFINED: // A user-defined parameter's values are a map of parameters UserDefinedParameter udp = (UserDefinedParameter) param; Map<String, Object> propvals = gson.fromJson(json, Map.class); // Iterate the new values and set it for the correct property value of the user-defined param for (Map.Entry<String, Object> propval : propvals.entrySet()) { Parameter sbp = udp.getProperty(propval.getKey()); if (sbp != null) { Scriptable s = mungeParam(sbp, (propval.getValue())); udp.setPropertyValue(propval.getKey(), (Parameter) s); } } wrapped = (Scriptable) Context.javaToJS(udp, scope); break; } } catch (IllegalArgumentException iae) { throw new IllegalArgumentException(iae.getMessage()); } catch (Exception e) { printf("Error parsing: %s\n", json); e.printStackTrace(); } return wrapped; }
From source file:blusunrize.immersiveengineering.common.crafting.IngredientFactoryFluidStack.java
@Nonnull @Override/* www.j av a 2s .c o m*/ public Ingredient parse(JsonContext context, JsonObject json) { String name = JsonUtils.getString(json, "fluid"); int amount = JsonUtils.getInt(json, "amount", 1000); Fluid fluid = FluidRegistry.getFluid(name); if (fluid == null) throw new JsonSyntaxException("Fluid with name " + name + " could not be found"); return new IngredientFluidStack(fluid, amount); }
From source file:blusunrize.immersiveengineering.common.crafting.RecipeFactoryShapedIngredient.java
@Override public IRecipe parse(JsonContext context, JsonObject json) { String group = JsonUtils.getString(json, "group", ""); Map<Character, Ingredient> ingMap = Maps.newHashMap(); for (Entry<String, JsonElement> entry : JsonUtils.getJsonObject(json, "key").entrySet()) { if (entry.getKey().length() != 1) throw new JsonSyntaxException("Invalid key entry: '" + entry.getKey() + "' is an invalid symbol (must be 1 character only)."); if (" ".equals(entry.getKey())) throw new JsonSyntaxException("Invalid key entry: ' ' is a reserved symbol."); ingMap.put(entry.getKey().toCharArray()[0], CraftingHelper.getIngredient(entry.getValue(), context)); }/* w w w . j av a 2s . c om*/ ingMap.put(' ', Ingredient.EMPTY); JsonArray patternJ = JsonUtils.getJsonArray(json, "pattern"); if (patternJ.size() == 0) throw new JsonSyntaxException("Invalid pattern: empty pattern not allowed"); String[] pattern = new String[patternJ.size()]; for (int x = 0; x < pattern.length; ++x) { String line = JsonUtils.getString(patternJ.get(x), "pattern[" + x + "]"); if (x > 0 && pattern[0].length() != line.length()) throw new JsonSyntaxException("Invalid pattern: each row must be the same width"); pattern[x] = line; } ShapedPrimer primer = new ShapedPrimer(); primer.width = pattern[0].length(); primer.height = pattern.length; primer.mirrored = JsonUtils.getBoolean(json, "mirrored", true); primer.input = NonNullList.withSize(primer.width * primer.height, Ingredient.EMPTY); Set<Character> keys = Sets.newHashSet(ingMap.keySet()); keys.remove(' '); int x = 0; for (String line : pattern) for (char chr : line.toCharArray()) { Ingredient ing = ingMap.get(chr); if (ing == null) throw new JsonSyntaxException( "Pattern references symbol '" + chr + "' but it's not defined in the key"); primer.input.set(x++, ing); keys.remove(chr); } if (!keys.isEmpty()) throw new JsonSyntaxException("Key defines symbols that aren't used in pattern: " + keys); ItemStack result = CraftingHelper.getItemStack(JsonUtils.getJsonObject(json, "result"), context); RecipeShapedIngredient recipe = new RecipeShapedIngredient( group.isEmpty() ? null : new ResourceLocation(group), result, primer); if (JsonUtils.getBoolean(json, "quarter_turn", false)) recipe.allowQuarterTurn(); if (JsonUtils.getBoolean(json, "eighth_turn", false)) recipe.allowEighthTurn(); if (JsonUtils.hasField(json, "copy_nbt")) { if (JsonUtils.isJsonArray(json, "copy_nbt")) { JsonArray jArray = JsonUtils.getJsonArray(json, "copy_nbt"); int[] array = new int[jArray.size()]; for (int i = 0; i < array.length; i++) array[i] = jArray.get(i).getAsInt(); recipe.setNBTCopyTargetRecipe(array); } else recipe.setNBTCopyTargetRecipe(JsonUtils.getInt(json, "copy_nbt")); if (JsonUtils.hasField(json, "copy_nbt_predicate")) recipe.setNBTCopyPredicate(JsonUtils.getString(json, "copy_nbt_predicate")); } return recipe; }
From source file:br.com.caelum.restfulie.gson.converters.DateTypeAdapter.java
License:Apache License
private synchronized Date deserializeToDate(String json) { for (DateFormat dateFormat : allDateFormats) { try {//from w ww .j a v a 2s. c om return dateFormat.parse(json); } catch (ParseException ignored) { // -- Passando para o prximo } } // -- No sei parsear isso, desisto! throw new JsonSyntaxException(json); }
From source file:cern.c2mon.shared.client.request.ClientRequestImpl.java
License:Open Source License
@Override public final Collection<T> fromJsonResponse(final String jsonString) throws JsonSyntaxException { Type collectionType;/*w w w . ja v a2 s .c o m*/ TypeReference jacksonCollectionType; JsonReader jsonReader = new JsonReader(new StringReader(jsonString)); jsonReader.setLenient(true); try { switch (resultType) { case TRANSFER_TAG_LIST: jacksonCollectionType = new TypeReference<Collection<TransferTagImpl>>() { }; return TransferTagSerializer.fromCollectionJson(jsonString, jacksonCollectionType); case TRANSFER_TAG_VALUE_LIST: jacksonCollectionType = new TypeReference<Collection<TransferTagValueImpl>>() { }; return TransferTagSerializer.fromCollectionJson(jsonString, jacksonCollectionType); case SUPERVISION_EVENT_LIST: collectionType = new TypeToken<Collection<SupervisionEventImpl>>() { }.getType(); return getGson().fromJson(jsonReader, collectionType); case TRANSFER_DAQ_XML: collectionType = new TypeToken<Collection<ProcessXmlResponseImpl>>() { }.getType(); return getGson().fromJson(jsonReader, collectionType); case TRANSFER_TAG_CONFIGURATION_LIST: collectionType = new TypeToken<Collection<TagConfigImpl>>() { }.getType(); return getGson().fromJson(jsonReader, collectionType); case TRANSFER_CONFIGURATION_REPORT_HEADER: collectionType = new TypeToken<Collection<ConfigurationReportHeader>>() { }.getType(); return getGson().fromJson(jsonReader, collectionType); case TRANSFER_CONFIGURATION_REPORT: collectionType = new TypeToken<Collection<ConfigurationReport>>() { }.getType(); return getGson().fromJson(jsonReader, collectionType); case TRANSFER_ACTIVE_ALARM_LIST: collectionType = new TypeToken<Collection<AlarmValueImpl>>() { }.getType(); return getGson().fromJson(jsonReader, collectionType); case TRANSFER_ALARM_LIST: collectionType = new TypeToken<Collection<AlarmValueImpl>>() { }.getType(); return getGson().fromJson(jsonReader, collectionType); case TRANSFER_COMMAND_HANDLES_LIST: collectionType = new TypeToken<Collection<CommandTagHandleImpl>>() { }.getType(); return getGson().fromJson(jsonReader, collectionType); case TRANSFER_COMMAND_REPORT: collectionType = new TypeToken<Collection<CommandReportImpl>>() { }.getType(); return getGson().fromJson(jsonReader, collectionType); case TRANSFER_PROCESS_NAMES: collectionType = new TypeToken<Collection<ProcessNameResponseImpl>>() { }.getType(); return getGson().fromJson(jsonReader, collectionType); case TRANSFER_DEVICE_CLASS_NAMES: collectionType = new TypeToken<Collection<DeviceClassNameResponseImpl>>() { }.getType(); return getGson().fromJson(jsonReader, collectionType); case TRANSFER_DEVICE_LIST: collectionType = new TypeToken<Collection<TransferDeviceImpl>>() { }.getType(); return getGson().fromJson(jsonReader, collectionType); case TRANSFER_TAG_STATISTICS: collectionType = new TypeToken<Collection<TagStatisticsResponseImpl>>() { }.getType(); return getGson().fromJson(jsonReader, collectionType); default: throw new JsonSyntaxException("Unknown result type specified"); } } finally { try { jsonReader.close(); } catch (IOException e) { } } }
From source file:cn.ieclipse.af.demo.sample.volley.adapter.IntAdapter.java
License:Apache License
@Override public Number read(JsonReader in) throws IOException { int num = 0;//from www. j av a 2s .c o m // 0 if (in.peek() == JsonToken.NULL) { in.nextNull(); num = 0; } else { try { double input = in.nextDouble();//?double?? num = (int) input;//int } catch (NumberFormatException e) { throw new JsonSyntaxException(e); } } return num; }
From source file:co.mitro.core.servlets.ServerRejectsServlet.java
License:Open Source License
/** * Sets the server hints to hintsString, after validation. Throws exceptions if the JSON data * is incorrect, although the validation isn't currently extremely careful. */// w w w . j av a 2 s . com public static void setServerHintsJson(String hintsString) { try { // Parse and validate the hints // TODO: Unit test this more carefully // can't use gson.fromJson() because it always uses lenient parsing; copied from there // See https://code.google.com/p/google-gson/issues/detail?id=372 JsonReader jsonReader = new JsonReader(new StringReader(hintsString)); TypeAdapter<?> typeAdapter = gson.getAdapter(TypeToken.get(listType)); @SuppressWarnings("unchecked") List<HintEntry> hints = (List<HintEntry>) typeAdapter.read(jsonReader); for (HintEntry hint : hints) { @SuppressWarnings("unused") Pattern regexp = Pattern.compile(hint.regex); if (hint.additional_submit_button_ids != null) { // optional: just don't include it instead of including an empty list assert hint.additional_submit_button_ids.size() > 0; for (String submitIds : hint.additional_submit_button_ids) { assert !Strings.isNullOrEmpty(submitIds); } } if (hint.allow_empty_username != null) { assert hint.allow_empty_username : "omit allow_empty_username if false"; } if (hint.empty_password_username_selector != null) { // TODO: Validate that this is a valid CSS selector? assert !hint.empty_password_username_selector .isEmpty() : "omit empty_password_username_selector if there is no selector"; assert hint.allow_empty_username != null && hint.allow_empty_username .booleanValue() : "allow_empty_username must be true if empty_password_username_selector is present"; } validateRules(hint.reject.login_submit); validateRules(hint.reject.submit); validateRules(hint.reject.password); validateRules(hint.reject.username); validateRules(hint.reject.form); } logger.info("setting {} server hints", hints.size()); serverHintsJson = hintsString; } catch (IOException | IllegalStateException e) { // Rethrow the same way as gson.fromJson() throw new JsonSyntaxException(e); } }
From source file:com.commonslibrary.commons.net.DefaultOkHttpIml.java
License:Open Source License
@SuppressWarnings("unchecked") private <T> void success(Response response, String result, RequestCallBack<T> callBack) { callBack.onSuccess(response.body().charStream()); Type type = getSuperClassGenricType(callBack.getClass(), 0); if (type == String.class) { callBack.onSuccess((T) result);/*from ww w .ja v a 2s . c o m*/ } else { try { T t = fromJson(result, type); if (t != null) { callBack.onSuccess(t); } else { callBack.onFailure("??", new JsonSyntaxException("??")); } } catch (Exception e) { e.printStackTrace(); callBack.onFailure("??", e); } } }
From source file:com.datastore_android_sdk.serialization.DateTypeAdapter.java
License:Apache License
private synchronized Date deserializeToDate(String json) { String jsonDateToMilliseconds = "\\/(Date\\((.*?)(\\+.*)?\\))\\/"; Pattern pattern = Pattern.compile(jsonDateToMilliseconds); Matcher matcher = pattern.matcher(json); String result = matcher.replaceAll("$2"); try {//from w w w.ja va 2 s.c o m return new Date(Long.valueOf(result)); } catch (Exception e) { throw new JsonSyntaxException(e); } }