com.google.gson.JsonParseException Java Examples
The following examples show how to use
com.google.gson.JsonParseException.
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: Toolbox.java From Slide with GNU General Public License v3.0 | 6 votes |
/** * Download a subreddit's usernotes * * @param subreddit */ public static void downloadUsernotes(String subreddit) { WikiManager manager = new WikiManager(Authentication.reddit); Gson gson = new GsonBuilder().registerTypeAdapter(new TypeToken<Map<String, List<Usernote>>>() {}.getType(), new Usernotes.BlobDeserializer()).create(); try { String data = manager.get(subreddit, "usernotes").getContent(); Usernotes result = gson.fromJson(data, Usernotes.class); cache.edit().putLong(subreddit + "_usernotes_timestamp", System.currentTimeMillis()).apply(); if (result != null && result.getSchema() == 6) { result.setSubreddit(subreddit); notes.put(subreddit, result); cache.edit().putBoolean(subreddit + "_usernotes_exists", true) .putString(subreddit + "_usernotes_data", data).apply(); } else { cache.edit().putBoolean(subreddit + "_usernotes_exists", false).apply(); } } catch (NetworkException | JsonParseException e) { if (e instanceof JsonParseException) { notes.remove(subreddit); } cache.edit().putLong(subreddit + "_usernotes_timestamp", System.currentTimeMillis()) .putBoolean(subreddit + "_usernotes_exists", false).apply(); } }
Example #2
Source File: All.java From dockerfile-image-update with BSD 3-Clause "New" or "Revised" License | 6 votes |
protected Set<Map.Entry<String, JsonElement>> parseStoreToImagesMap(String storeName) throws IOException, InterruptedException { GHMyself myself = dockerfileGitHubUtil.getMyself(); String login = myself.getLogin(); GHRepository store = dockerfileGitHubUtil.getRepo(Paths.get(login, storeName).toString()); GHContent storeContent = dockerfileGitHubUtil.tryRetrievingContent(store, Constants.STORE_JSON_FILE, store.getDefaultBranch()); if (storeContent == null) { return Collections.emptySet(); } JsonElement json; try (InputStream stream = storeContent.read(); InputStreamReader streamR = new InputStreamReader(stream)) { try { json = JsonParser.parseReader(streamR); } catch (JsonParseException e) { log.warn("Not a JSON format store."); return Collections.emptySet(); } } JsonElement imagesJson = json.getAsJsonObject().get("images"); return imagesJson.getAsJsonObject().entrySet(); }
Example #3
Source File: AllocatedGroupRangeDeserializer.java From Android-nRF-Mesh-Library with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Override public List<AllocatedGroupRange> deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException { final List<AllocatedGroupRange> groupRanges = new ArrayList<>(); try { final JsonArray jsonObject = json.getAsJsonArray(); for (int i = 0; i < jsonObject.size(); i++) { final JsonObject unicastRangeJson = jsonObject.get(i).getAsJsonObject(); final int lowAddress = Integer.parseInt(unicastRangeJson.get("lowAddress").getAsString(), 16); final int highAddress = Integer.parseInt(unicastRangeJson.get("highAddress").getAsString(), 16); groupRanges.add(new AllocatedGroupRange(lowAddress, highAddress)); } } catch (Exception ex) { Log.e(TAG, "Error while de-serializing Allocated group range: " + ex.getMessage()); } return groupRanges; }
Example #4
Source File: SerializationTests.java From azure-mobile-apps-android-client with Apache License 2.0 | 6 votes |
public void testCustomDeserializationUsingWithoutUsingMobileServiceTable() { String serializedObject = "{\"address\":{\"zipcode\":1313,\"country\":\"US\",\"streetaddress\":\"1345 Washington St\"},\"firstName\":\"John\",\"lastName\":\"Doe\"}"; JsonObject jsonObject = new JsonParser().parse(serializedObject).getAsJsonObject(); gsonBuilder.registerTypeAdapter(Address.class, new JsonDeserializer<Address>() { @Override public Address deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { Address a = new Address(arg0.getAsJsonObject().get("streetaddress").getAsString(), arg0.getAsJsonObject().get("zipcode").getAsInt(), arg0 .getAsJsonObject().get("country").getAsString()); return a; } }); ComplexPersonTestObject deserializedPerson = gsonBuilder.create().fromJson(jsonObject, ComplexPersonTestObject.class); // Asserts assertEquals("John", deserializedPerson.getFirstName()); assertEquals("Doe", deserializedPerson.getLastName()); assertEquals(1313, deserializedPerson.getAddress().getZipCode()); assertEquals("US", deserializedPerson.getAddress().getCountry()); assertEquals("1345 Washington St", deserializedPerson.getAddress().getStreetAddress()); }
Example #5
Source File: LocationService.java From FineGeotag with GNU General Public License v3.0 | 6 votes |
public Location deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jObject = (JsonObject) json; Location location = new Location(jObject.get("Provider").getAsString()); location.setTime(jObject.get("Time").getAsLong()); location.setLatitude(jObject.get("Latitude").getAsDouble()); location.setLongitude(jObject.get("Longitude").getAsDouble()); if (jObject.has("Altitude")) location.setAltitude(jObject.get("Altitude").getAsDouble()); if (jObject.has("Speed")) location.setSpeed(jObject.get("Speed").getAsFloat()); if (jObject.has("Bearing")) location.setBearing(jObject.get("Bearing").getAsFloat()); if (jObject.has("Accuracy")) location.setAccuracy(jObject.get("Accuracy").getAsFloat()); return location; }
Example #6
Source File: AllocatedGroupRangeDbMigrator.java From Android-nRF-Mesh-Library with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Override public List<AllocatedGroupRange> deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException { final List<AllocatedGroupRange> groupRanges = new ArrayList<>(); try { if(json.isJsonArray()) { final JsonArray jsonObject = json.getAsJsonArray(); for (int i = 0; i < jsonObject.size(); i++) { final JsonObject unicastRangeJson = jsonObject.get(i).getAsJsonObject(); final int lowAddress = unicastRangeJson.get("lowAddress").getAsInt(); final int highAddress = unicastRangeJson.get("highAddress").getAsInt(); groupRanges.add(new AllocatedGroupRange(lowAddress, highAddress)); } } } catch (Exception ex) { Log.e(TAG, "Error while de-serializing Allocated group range: " + ex.getMessage()); } return groupRanges; }
Example #7
Source File: JsonHandler.java From dhis2-android-datacapture with BSD 3-Clause "New" or "Revised" License | 6 votes |
public static JsonObject buildJsonObject(String json) throws ParsingException { if (json == null) { throw new ParsingException("Cannot parse empty json"); } JsonReader reader = new JsonReader(new StringReader(json)); reader.setLenient(true); try { JsonElement jRawSource = new JsonParser().parse(reader); if (jRawSource != null && jRawSource.isJsonObject()) { return jRawSource.getAsJsonObject(); } else { throw new ParsingException("The incoming Json is bad/malicious"); } } catch (JsonParseException e) { throw new ParsingException("The incoming Json is bad/malicious"); } }
Example #8
Source File: RoutingConfigAdapter.java From cosmic with Apache License 2.0 | 6 votes |
@Override public RoutingConfig deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext context) throws JsonParseException { final JsonObject jsonObject = jsonElement.getAsJsonObject(); if (!jsonObject.has("type")) { throw new JsonParseException("Deserializing as a RoutingConfig, but no type present in the json object"); } final String routingConfigType = jsonObject.get("type").getAsString(); if (SINGLE_DEFAULT_ROUTE_IMPLICIT_ROUTING_CONFIG.equals(routingConfigType)) { return context.deserialize(jsonElement, SingleDefaultRouteImplicitRoutingConfig.class); } else if (ROUTING_TABLE_ROUTING_CONFIG.equals(routingConfigType)) { return context.deserialize(jsonElement, RoutingTableRoutingConfig.class); } throw new JsonParseException("Failed to deserialize type \"" + routingConfigType + "\""); }
Example #9
Source File: JSON.java From director-sdk with Apache License 2.0 | 6 votes |
/** * Deserialize the given JSON string to Java object. * * @param <T> Type * @param body The JSON string * @param returnType The type to deserialize into * @return The deserialized Java object */ @SuppressWarnings("unchecked") public <T> T deserialize(String body, Type returnType) { try { if (isLenientOnJson) { JsonReader jsonReader = new JsonReader(new StringReader(body)); // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) jsonReader.setLenient(true); return gson.fromJson(jsonReader, returnType); } else { return gson.fromJson(body, returnType); } } catch (JsonParseException e) { // Fallback processing when failed to parse JSON form response body: // return the response body string directly for the String return type; if (returnType.equals(String.class)) return (T) body; else throw e; } }
Example #10
Source File: DateDeserializer.java From quill with MIT License | 6 votes |
@Override public Date deserialize(JsonElement element, Type type, JsonDeserializationContext context) throws JsonParseException { String date = element.getAsString(); @SuppressLint("SimpleDateFormat") SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); formatter.setTimeZone(TimeZone.getTimeZone("UTC")); try { return formatter.parse(date); } catch (ParseException e) { Log.e(TAG, "Parsing failed: " + Log.getStackTraceString(e)); return new Date(); } }
Example #11
Source File: JsonCodec.java From iot-java with Eclipse Public License 1.0 | 6 votes |
@Override public JsonMessage decode(MqttMessage msg) throws MalformedMessageException { JsonObject data; if (msg.getPayload().length == 0) { data = null; } else { try { final String payloadInString = new String(msg.getPayload(), "UTF8"); data = JSON_PARSER.parse(payloadInString).getAsJsonObject(); } catch (JsonParseException | UnsupportedEncodingException e) { throw new MalformedMessageException("Unable to parse JSON: " + e.toString()); } } return new JsonMessage(data, null); }
Example #12
Source File: HarvesterAnimationStateMachine.java From EmergingTechnology with MIT License | 6 votes |
/** * post-loading initialization hook. */ void initialize() { if (parameters == null) { throw new JsonParseException("Animation State Machine should contain \"parameters\" key."); } if (clips == null) { throw new JsonParseException("Animation State Machine should contain \"clips\" key."); } if (states == null) { throw new JsonParseException("Animation State Machine should contain \"states\" key."); } if (transitions == null) { throw new JsonParseException("Animation State Machine should contain \"transitions\" key."); } shouldHandleSpecialEvents = true; lastPollTime = Float.NEGATIVE_INFINITY; // setting the starting state IClip state = clips.get(startState); if (!clips.containsKey(startState) || !states.contains(startState)) { throw new IllegalStateException("unknown state: " + startState); } currentStateName = startState; currentState = state; }
Example #13
Source File: WindowPropertiesSerializer.java From paintera with GNU General Public License v2.0 | 6 votes |
@Override public WindowProperties deserialize( final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException { final WindowProperties properties = new WindowProperties(); if (json.isJsonObject()) { final JsonObject map = json.getAsJsonObject(); if (map.has(WIDTH_KEY)) properties.widthProperty.set(map.get(WIDTH_KEY).getAsInt()); if (map.has(HEIGHT_KEY)) properties.heightProperty.set(map.get(HEIGHT_KEY).getAsInt()); if (map.has(IS_FULL_SCREEN_KEY)) properties.isFullScreen.set(map.get(IS_FULL_SCREEN_KEY).getAsBoolean()); properties.clean(); } return properties; }
Example #14
Source File: LookupSwitchInsnNodeSerializer.java From maple-ir with GNU General Public License v3.0 | 6 votes |
@Override public LookupSwitchInsnNode deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = (JsonObject) json; LabelNode dflt = context.deserialize(jsonObject.get("dflt"), LabelNode.class); List<Integer> keysList = context.deserialize(jsonObject.get("keys"), List.class); List<LabelNode> labelsList = context.deserialize(jsonObject.get("labels"), List.class); int[] keys = new int[keysList.size()]; for(int i=0; i < keys.length; i++){ keys[i] = keysList.get(i); } LabelNode[] labels = new LabelNode[labelsList.size()]; for(int i=0; i < labels.length; i++){ labels[i] = labelsList.get(i); } return new LookupSwitchInsnNode(dflt, keys, labels); }
Example #15
Source File: FilterChainStepSerializer.java From storm-dynamic-spout with BSD 3-Clause "New" or "Revised" License | 6 votes |
@SuppressWarnings("unchecked") private Class<T> getClassInstance() { @SuppressWarnings("unchecked") final String className = (String) config.get(SidelineConfig.FILTER_CHAIN_STEP_CLASS); Preconditions.checkArgument( className != null && !className.isEmpty(), "A valid class name must be specified for " + SidelineConfig.FILTER_CHAIN_STEP_CLASS ); try { return (Class<T>) Class.forName(className); } catch (ClassNotFoundException cnfe) { throw new JsonParseException(cnfe.getMessage()); } }
Example #16
Source File: DeviceHiveWebSocketHandler.java From devicehive-java-server with Apache License 2.0 | 6 votes |
@Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { logger.error("Error in session {}: {}", session.getId(), exception.getMessage()); if (exception.getMessage().contains("Connection reset by peer")) { afterConnectionClosed(session, CloseStatus.SESSION_NOT_RELIABLE); return; } JsonMessageBuilder builder; session = sessionMonitor.getSession(session.getId()); if (exception instanceof JsonParseException) { builder = JsonMessageBuilder .createErrorResponseBuilder(HttpServletResponse.SC_BAD_REQUEST, "Incorrect JSON syntax"); } else { builder = JsonMessageBuilder .createErrorResponseBuilder(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error"); } try { session.sendMessage(new TextMessage(GsonFactory.createGson().toJson(builder.build()))); } catch (ClosedChannelException closedChannelException) { logger.error("WebSocket error: Channel is closed"); } }
Example #17
Source File: FeatureTypeAdapter.java From VoxelGamesLibv2 with MIT License | 6 votes |
@Override @Nullable public Feature deserialize(@Nonnull JsonElement json, @Nonnull Type typeOfT, @Nonnull JsonDeserializationContext context) throws JsonParseException { try { JsonObject jsonObject = json.getAsJsonObject(); // default path String name = jsonObject.get("name").getAsString(); if (!name.contains(".")) { name = DEFAULT_PATH + "." + name; } Class<?> clazz = Class.forName(name); Feature feature = context.deserialize(json, clazz); injector.injectMembers(feature); return feature; } catch (Exception e) { log.log(Level.WARNING, "Could not deserialize feature:\n" + json.toString(), e); } return null; }
Example #18
Source File: VolumeApiServiceImpl.java From cloudstack with Apache License 2.0 | 6 votes |
public void updateMissingRootDiskController(final VMInstanceVO vm, final String rootVolChainInfo) { if (vm == null || !VirtualMachine.Type.User.equals(vm.getType()) || Strings.isNullOrEmpty(rootVolChainInfo)) { return; } String rootDiskController = null; try { final VirtualMachineDiskInfo infoInChain = _gson.fromJson(rootVolChainInfo, VirtualMachineDiskInfo.class); if (infoInChain != null) { rootDiskController = infoInChain.getControllerFromDeviceBusName(); } final UserVmVO userVmVo = _userVmDao.findById(vm.getId()); if ((rootDiskController != null) && (!rootDiskController.isEmpty())) { _userVmDao.loadDetails(userVmVo); _userVmMgr.persistDeviceBusInfo(userVmVo, rootDiskController); } } catch (JsonParseException e) { s_logger.debug("Error parsing chain info json: " + e.getMessage()); } }
Example #19
Source File: Request.java From cloudstack with Apache License 2.0 | 6 votes |
@Override public Pair<Long, Long> deserialize(JsonElement json, java.lang.reflect.Type type, JsonDeserializationContext context) throws JsonParseException { Pair<Long, Long> pairs = new Pair<Long, Long>(null, null); JsonArray array = json.getAsJsonArray(); if (array.size() != 2) { return pairs; } JsonElement element = array.get(0); if (!element.isJsonNull()) { pairs.first(element.getAsLong()); } element = array.get(1); if (!element.isJsonNull()) { pairs.second(element.getAsLong()); } return pairs; }
Example #20
Source File: ImageProfileController.java From uyuni with GNU General Public License v2.0 | 6 votes |
/** * Processes a DELETE request * * @param req the request object * @param res the response object * @param user the authorized user * @return the result JSON object */ public static Object delete(Request req, Response res, User user) { List<Long> ids; try { ids = Arrays.asList(GSON.fromJson(req.body(), Long[].class)); } catch (JsonParseException e) { Spark.halt(HttpStatus.SC_BAD_REQUEST); return null; } List<ImageProfile> profiles = ImageProfileFactory.lookupByIdsAndOrg(ids, user.getOrg()); if (profiles.size() < ids.size()) { return json(res, ResultJson.error("not_found")); } profiles.forEach(ImageProfileFactory::delete); return json(res, ResultJson.success(profiles.size())); }
Example #21
Source File: Cryptsy.java From cryptsy-api with GNU Lesser General Public License v3.0 | 6 votes |
public Balances deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Balances balances = new Balances(); if (json.isJsonObject()) { JsonObject o = json.getAsJsonObject(); List<Market> markets = new ArrayList<Market>(); Iterator<Entry<String, JsonElement>> iter = o.entrySet() .iterator(); while (iter.hasNext()) { Entry<String, JsonElement> jsonOrder = iter.next(); String currency = jsonOrder.getKey(); double balance = context.deserialize(jsonOrder.getValue(), Double.class); balances.put(currency, balance); } } return balances; }
Example #22
Source File: FilesDatasetSourceConfig.java From mr4c with Apache License 2.0 | 5 votes |
private static DirectoryConfig loadDirectoryConfig(Reader reader) throws IOException { ConfigSerializer ser = SerializerFactories.getSerializerFactory("application/json").createConfigSerializer(); // assume json config for now ser = new ParameterizedConfigSerializer(ser); String content = IOUtils.toString(reader); // need to get this so we can read it twice try { return ser.deserializeDirectoryConfig(new StringReader(content)); } catch ( JsonParseException jpe ) { s_log.warn("Json deserialization failed; trying as properties", jpe); Properties props = new Properties(); props.load(new StringReader(content)); return DirectoryConfig.createFromProperties(props); } }
Example #23
Source File: ListenNowStationDeserializer.java From gplaymusic with MIT License | 5 votes |
@Override public ListenNowStation deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException { JsonObject content = je.getAsJsonObject(); ListenNowStation station = gson.fromJson(je, ListenNowStation.class); JsonArray seeds = content.getAsJsonObject("id").getAsJsonArray("seeds"); for (JsonElement seed : seeds) { station.addSeed(jdc.deserialize(seed, StationSeed.class)); } return station; }
Example #24
Source File: LocalFileCodec.java From twill with Apache License 2.0 | 5 votes |
@Override public LocalFile deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObj = json.getAsJsonObject(); String name = jsonObj.get("name").getAsString(); URI uri = URI.create(jsonObj.get("uri").getAsString()); long lastModified = jsonObj.get("lastModified").getAsLong(); long size = jsonObj.get("size").getAsLong(); boolean archive = jsonObj.get("archive").getAsBoolean(); JsonElement pattern = jsonObj.get("pattern"); return new DefaultLocalFile(name, uri, lastModified, size, archive, (pattern == null || pattern.isJsonNull()) ? null : pattern.getAsString()); }
Example #25
Source File: Key.java From java-cloudant with Apache License 2.0 | 5 votes |
@Override public Key.ComplexKey deserialize(JsonElement json, java.lang.reflect.Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (json.isJsonArray()) { ComplexKey key = new ComplexKey(json.getAsJsonArray()); return key; } else { return null; } }
Example #26
Source File: GsonParser.java From QuickDevFramework with Apache License 2.0 | 5 votes |
@Override public String deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try { return json.getAsString(); } catch (Exception e) { return json.toString(); } }
Example #27
Source File: ScheduleDataManager4ZK.java From tbschedule with Apache License 2.0 | 5 votes |
@Override public Timestamp deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (!(json instanceof JsonPrimitive)) { throw new JsonParseException("The date should be a string value"); } try { DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = (Date) format.parse(json.getAsString()); return new Timestamp(date.getTime()); } catch (Exception e) { throw new JsonParseException(e); } }
Example #28
Source File: ParseHelper.java From WheelPicker with Apache License 2.0 | 5 votes |
@Override public String deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try { return json.getAsString(); } catch (Exception e) { return ""; } }
Example #29
Source File: AlexaMessageFacadeSerDer.java From arcusplatform with Apache License 2.0 | 5 votes |
@Override public AlexaMessage deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject obj = json.getAsJsonObject(); if(obj.has(SerDer.ATTR_DIRECTIVE)) { return v3.deserialize(json, typeOfT, context); } return v2.deserialize(json, typeOfT, context); }
Example #30
Source File: DateDeserializer.java From udacity-p1-p2-popular-movies with MIT License | 5 votes |
@Override public Date deserialize(JsonElement element, Type type, JsonDeserializationContext context) throws JsonParseException { String date = element.getAsString(); @SuppressLint("SimpleDateFormat") SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); try { return formatter.parse(date); } catch (ParseException e) { Log.e(TAG, "Parsing failed: " + Log.getStackTraceString(e)); return new Date(); } }