List of usage examples for com.google.gson JsonElement getAsString
public String getAsString()
From source file:com.google.code.stackexchange.client.impl.StackExchangeApiJsonClient.java
License:Apache License
protected GsonBuilder getGsonBuilder() { GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { @Override//from w w w . j a v a 2 s . c om public Date deserialize(JsonElement source, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return new Date(source.getAsLong() * 1000); } }); builder.registerTypeAdapter(BadgeRank.class, new JsonDeserializer<BadgeRank>() { @Override public BadgeRank deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return BadgeRank.fromValue(arg0.getAsString()); } }); builder.registerTypeAdapter(PostType.class, new JsonDeserializer<PostType>() { @Override public PostType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return PostType.fromValue(arg0.getAsString()); } }); builder.registerTypeAdapter(PostTimelineType.class, new JsonDeserializer<PostTimelineType>() { @Override public PostTimelineType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return PostTimelineType.fromValue(arg0.getAsString()); } }); builder.registerTypeAdapter(UserTimelineType.class, new JsonDeserializer<UserTimelineType>() { @Override public UserTimelineType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return UserTimelineType.fromValue(arg0.getAsString()); } }); builder.registerTypeAdapter(UserType.class, new JsonDeserializer<UserType>() { @Override public UserType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return UserType.fromValue(arg0.getAsString()); } }); builder.registerTypeAdapter(RevisionType.class, new JsonDeserializer<RevisionType>() { @Override public RevisionType deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return RevisionType.fromValue(arg0.getAsString()); } }); builder.registerTypeAdapter(TagRestriction.class, new JsonDeserializer<TagRestriction>() { @Override public TagRestriction deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return TagRestriction.fromValue(arg0.getAsString()); } }); builder.registerTypeAdapter(SiteState.class, new JsonDeserializer<SiteState>() { @Override public SiteState deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException { return SiteState.fromValue(arg0.getAsString()); } }); builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); return builder; }
From source file:com.google.dart.server.internal.remote.processor.JsonProcessor.java
License:Open Source License
/** * Safely get some member off of the passed {@link JsonObject} and return the {@link String}. * Instead of calling {@link JsonObject#has(String)} before {@link JsonObject#get(String)}, only * one call to the {@link JsonObject} is made in order to be faster. The result will be * {@code null} if the member is not on the {@link JsonObject}. This is used for optional json * parameters.// w w w . ja v a 2 s . c om * * @param jsonObject the {@link JsonObject} * @param memberName the member name * @return the looked up {@link String}, or {@code null} */ protected String safelyGetAsString(JsonObject jsonObject, String memberName) { JsonElement jsonElement = jsonObject.get(memberName); if (jsonElement == null) { return null; } else { return jsonElement.getAsString(); } }
From source file:com.google.dart.server.internal.remote.processor.NotificationExecutionLaunchDataProcessor.java
License:Open Source License
@Override public void process(JsonObject response) throws Exception { JsonObject paramsObject = response.get("params").getAsJsonObject(); String file = paramsObject.get("file").getAsString(); JsonElement jsonKind = paramsObject.get("kind"); String kind = jsonKind == null ? null : jsonKind.getAsString(); JsonElement jsonFiles = paramsObject.get("referencedFiles"); JsonArray referencedFiles = jsonFiles == null ? null : jsonFiles.getAsJsonArray(); getListener().computedLaunchData(file, kind, constructStringArray(referencedFiles)); }
From source file:com.google.dart.server.internal.remote.processor.NotificationServerConnectedProcessor.java
License:Open Source License
private String getVersion(JsonObject response) { JsonElement paramsElement = response.get("params"); if (paramsElement != null) { JsonElement versionElement = paramsElement.getAsJsonObject().get("version"); if (versionElement != null) { return versionElement.getAsString(); }/* w w w .jav a2s.c o m*/ } return null; }
From source file:com.google.dart.server.internal.remote.RemoteAnalysisServerImpl.java
License:Open Source License
/** * Attempts to handle the given {@link JsonObject} as a notification. Return {@code true} if it * was handled, otherwise {@code false} is returned. * * @return {@code true} if it was handled, otherwise {@code false} is returned *///from w ww. j av a 2 s . c om private boolean processNotification(JsonObject response) throws Exception { // prepare notification kind JsonElement eventElement = response.get("event"); if (eventElement == null || !eventElement.isJsonPrimitive()) { return false; } String event = eventElement.getAsString(); // handle each supported notification kind if (event.equals(ANALYSIS_NOTIFICATION_ERRORS)) { // analysis.errors new NotificationAnalysisErrorsProcessor(listener).process(response); } else if (event.equals(ANALYSIS_NOTIFICATION_FLUSH_RESULTS)) { // analysis.flushResults new NotificationAnalysisFlushResultsProcessor(listener).process(response); } else if (event.equals(ANALYSIS_NOTIFICATION_HIGHTLIGHTS)) { // analysis.highlights new NotificationAnalysisHighlightsProcessor(listener).process(response); } else if (event.equals(ANALYSIS_NOTIFICATION_IMPLEMENTED)) { // analysis.implemented new NotificationAnalysisImplementedProcessor(listener).process(response); } else if (event.equals(ANALYSIS_NOTIFICATION_NAVIGATION)) { // analysis.navigation new NotificationAnalysisNavigationProcessor(listener).process(response); } else if (event.equals(ANALYSIS_NOTIFICATION_OCCURRENCES)) { // analysis.occurrences new NotificationAnalysisOccurrencesProcessor(listener).process(response); } else if (event.equals(ANALYSIS_NOTIFICATION_OUTLINE)) { // analysis.outline new NotificationAnalysisOutlineProcessor(listener).process(response); } else if (event.equals(ANALYSIS_NOTIFICATION_OVERRIDES)) { // analysis.overrides new NotificationAnalysisOverridesProcessor(listener).process(response); } else if (event.equals(ANALYSIS_NOTIFICATION_ANALYZED_FILES)) { // analysis.errors new NotificationAnalysisAnalyzedFilesProcessor(listener).process(response); } else if (event.equals(COMPLETION_NOTIFICATION_RESULTS)) { // completion.results new NotificationCompletionResultsProcessor(listener).process(response); } else if (event.equals(SEARCH_NOTIFICATION_RESULTS)) { // search.results new NotificationSearchResultsProcessor(listener).process(response); } else if (event.equals(SERVER_NOTIFICATION_STATUS)) { // server.status new NotificationServerStatusProcessor(listener).process(response); } else if (event.equals(SERVER_NOTIFICATION_ERROR)) { // server.error new NotificationServerErrorProcessor(listener).process(response); } else if (event.equals(SERVER_NOTIFICATION_CONNECTED)) { // server.connected new NotificationServerConnectedProcessor(listener).process(response); } else if (event.equals(LAUNCH_DATA_NOTIFICATION_RESULTS)) { new NotificationExecutionLaunchDataProcessor(listener).process(response); } // it is a notification, even if we did not handle it return true; }
From source file:com.google.dart.server.internal.remote.utilities.RequestUtilities.java
License:Open Source License
/** * Returns the request method, or {@code null}. *//*from www . j a v a 2 s . com*/ private static String getRequestMethod(JsonObject request) { JsonElement child = request.get(METHOD); if (child instanceof JsonPrimitive) { return child.getAsString(); } return null; }
From source file:com.google.devfestnorte.server.APIUpdater.java
License:Open Source License
private ManifestData extractManifestData(JsonObject currentManifest, ManifestData copyFrom) { ManifestData data = new ManifestData(); data.majorVersion = copyFrom == null ? Config.MANIFEST_VERSION : copyFrom.majorVersion; data.minorVersion = copyFrom == null ? 0 : copyFrom.minorVersion; data.dataFiles = new JsonArray(); if (currentManifest != null) { try {/*ww w . j av a 2 s . co m*/ JsonArray files = currentManifest.get("data_files").getAsJsonArray(); for (JsonElement file : files) { String filename = file.getAsString(); Matcher matcher = Config.SESSIONS_PATTERN.matcher(filename); if (matcher.matches()) { // versions numbers are only extracted from the existing session filename if copyFrom is null. if (copyFrom == null) { data.majorVersion = Integer.parseInt(matcher.group(1)); data.minorVersion = Integer.parseInt(matcher.group(2)); } } else { data.dataFiles.add(file); } } } catch (NullPointerException ex) { Logger.getLogger(getClass().getName()) .warning("Ignoring existing manifest, as it seems " + "to be badly formatted."); } catch (NumberFormatException ex) { Logger.getLogger(getClass().getName()) .warning("Ignoring existing manifest, as it seems " + "to be badly formatted."); } } if (copyFrom == null) { // Increment the minor version data.minorVersion++; data.sessionsFilename = MessageFormat.format(Config.SESSIONS_FORMAT, data.majorVersion, data.minorVersion); } else { data.sessionsFilename = copyFrom.sessionsFilename; } data.dataFiles.add(new JsonPrimitive(data.sessionsFilename)); return data; }
From source file:com.google.gdt.googleapi.core.ApiDirectoryListingJsonCodec.java
License:Open Source License
protected void populateApiInfoFromJson(URL baseURL, JsonObject object, MutableApiInfo info) { if (object.has("name")) { info.setName(object.get("name").getAsString()); }/*from w ww . ja v a 2 s. c o m*/ if (object.has("version")) { info.setVersion(object.get("version").getAsString()); } if (object.has("title")) { info.setDisplayName(object.get("title").getAsString()); } if (object.has("publisher")) { info.setPublisher(object.get("publisher").getAsString()); } if (object.has("description")) { info.setDescription(object.get("description").getAsString()); } if (object.has("icons")) { JsonObject iconLinks = object.getAsJsonObject("icons"); Set<Entry<String, JsonElement>> iconLinksEntrySet = iconLinks.entrySet(); for (Entry<String, JsonElement> entry : iconLinksEntrySet) { try { info.putIconLink(entry.getKey(), new URL(baseURL, entry.getValue().getAsString())); } catch (MalformedURLException e) { // TODO Add logging warn } } } if (object.has("labels")) { JsonArray labelsJsonArray = object.getAsJsonArray("labels"); for (JsonElement labelElement : labelsJsonArray) { info.addLabel(labelElement.getAsString()); } } if (object.has("releaseDate")) { try { LocalDate date = new LocalDate(object.get("releaseDate").getAsString()); info.setReleaseDate(date); } catch (IllegalArgumentException e) { throw new JsonParseException(e); } } if (object.has("releaseNotesLink")) { try { info.setReleaseNotesLink(new URL(baseURL, object.get("releaseNotesLink").getAsString())); } catch (MalformedURLException e) { // TODO Add logging warn } } if (object.has("ranking")) { info.setRanking(object.get("ranking").getAsInt()); } if (object.has("discoveryLink")) { try { info.setDiscoveryLink(new URL(baseURL, object.get("discoveryLink").getAsString())); } catch (MalformedURLException e) { // TODO Add logging warn } } if (object.has("documentationLink")) { try { info.setDocumentationLink(new URL(baseURL, object.get("documentationLink").getAsString())); } catch (MalformedURLException e) { // TODO Add logging warn } } if (object.has("downloadLink")) { try { info.setDownloadLink(new URL(baseURL, object.get("downloadLink").getAsString())); } catch (MalformedURLException e) { // TODO Add logging warn } } if (object.has("tosLink")) { try { info.setTosLink(new URL(baseURL, object.get("tosLink").getAsString())); } catch (MalformedURLException e) { // TODO Add logging warn } } }
From source file:com.google.gerrit.httpd.TokenVerifiedRestApiServlet.java
License:Apache License
private static ParsedBody parseJson(HttpServletRequest req, HttpServletResponse res) throws IOException { try {/*w ww . jav a 2 s .co m*/ JsonElement element = new JsonParser().parse(req.getReader()); if (!element.isJsonObject()) { sendError(res, SC_BAD_REQUEST, "Expected JSON object in request body"); return null; } ParsedBody body = new ParsedBody(); body.req = req; body.json = (JsonObject) element; JsonElement authKey = body.json.remove(AUTHKEY_NAME); if (authKey != null && authKey.isJsonPrimitive() && authKey.getAsJsonPrimitive().isString()) { body._authkey = authKey.getAsString(); } return body; } catch (JsonParseException e) { sendError(res, SC_BAD_REQUEST, "Invalid JSON object in request body"); return null; } }
From source file:com.google.gwtjsonrpc.server.CallDeserializer.java
License:Apache License
public CallType deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException, NoSuchRemoteMethodException { if (!json.isJsonObject()) { throw new JsonParseException("Expected object"); }/* w w w .j av a 2 s . com*/ final JsonObject in = json.getAsJsonObject(); req.id = in.get("id"); final JsonElement jsonrpc = in.get("jsonrpc"); final JsonElement version = in.get("version"); if (isString(jsonrpc) && version == null) { final String v = jsonrpc.getAsString(); if ("2.0".equals(v)) { req.versionName = "jsonrpc"; req.versionValue = jsonrpc; } else { throw new JsonParseException("Expected jsonrpc=2.0"); } } else if (isString(version) && jsonrpc == null) { final String v = version.getAsString(); if ("1.1".equals(v)) { req.versionName = "version"; req.versionValue = version; } else { throw new JsonParseException("Expected version=1.1"); } } else { throw new JsonParseException("Expected version=1.1 or jsonrpc=2.0"); } final JsonElement method = in.get("method"); if (!isString(method)) { throw new JsonParseException("Expected method name as string"); } req.method = server.lookupMethod(method.getAsString()); if (req.method == null) { throw new NoSuchRemoteMethodException(); } final JsonElement callback = in.get("callback"); if (callback != null) { if (!isString(callback)) { throw new JsonParseException("Expected callback as string"); } req.callback = callback.getAsString(); } final JsonElement xsrfKey = in.get("xsrfKey"); if (xsrfKey != null) { if (!isString(xsrfKey)) { throw new JsonParseException("Expected xsrfKey as string"); } req.xsrfKeyIn = xsrfKey.getAsString(); } final Type[] paramTypes = req.method.getParamTypes(); final JsonElement params = in.get("params"); if (params != null) { if (!params.isJsonArray()) { throw new JsonParseException("Expected params array"); } final JsonArray paramsArray = params.getAsJsonArray(); if (paramsArray.size() != paramTypes.length) { throw new JsonParseException("Expected " + paramTypes.length + " parameter values in params array"); } final Object[] r = new Object[paramTypes.length]; for (int i = 0; i < r.length; i++) { final JsonElement v = paramsArray.get(i); if (v != null) { r[i] = context.deserialize(v, paramTypes[i]); } } req.params = r; } else { if (paramTypes.length != 0) { throw new JsonParseException("Expected params array"); } req.params = JsonServlet.NO_PARAMS; } return req; }