List of usage examples for com.google.gson JsonPrimitive getAsString
@Override
public String getAsString()
From source file:com.github.maoo.indexer.client.WebScriptsAlfrescoClient.java
License:Apache License
private List<String> getAuthorities(JsonObject userObject) { List<String> authorities = new ArrayList<String>(); if (!userObject.has(AUTHORITIES)) { throw new AlfrescoParseException("Json response is authorities."); }//from ww w.j ava2 s.c om JsonElement authoritiesElement = userObject.get(AUTHORITIES); if (!authoritiesElement.isJsonArray()) { throw new AlfrescoParseException( "Authorities must be a json array. It was: " + authoritiesElement.toString()); } JsonArray authoritiesArray = authoritiesElement.getAsJsonArray(); for (JsonElement authorityElement : authoritiesArray) { if (!authorityElement.isJsonPrimitive()) { throw new AlfrescoParseException( "Authority entry must be a string. It was: " + authoritiesElement.toString()); } JsonPrimitive authorityPrimitive = authorityElement.getAsJsonPrimitive(); if (!authorityPrimitive.isString()) { throw new AlfrescoParseException( "Authority entry must be a string. It was: " + authoritiesElement.toString()); } authorities.add(authorityPrimitive.getAsString()); } return authorities; }
From source file:com.github.strawberry.util.Json.java
License:Open Source License
public static Object parsePrimitive(JsonElement e) { JsonPrimitive p = e.getAsJsonPrimitive(); if (p.isString()) { return e.getAsString(); }// www.j a va2 s.co m if (p.isBoolean()) { return e.getAsBoolean(); } if (p.isNumber()) { return e.getAsInt(); } return p.getAsString(); }
From source file:com.google.appinventor.components.runtime.GoogleMap.java
License:Open Source License
@SimpleFunction(description = "Adding a list of markers that are represented as JsonArray. " + " The inner JsonObject represents a marker" + "and is composed of name-value pairs. Name fields for a marker are: " + "\"lat\" (type double) [required], \"lng\"(type double) [required], " + "\"color\"(type int)[in hue value ranging from 0~360], " + "\"title\"(type String), \"snippet\"(type String), \"draggable\"(type boolean)") public void AddMarkersFromJson(String jsonString) { ArrayList<Integer> markerIds = new ArrayList<Integer>(); JsonParser parser = new JsonParser(); float[] hsv = new float[3]; // parse jsonString into jsonArray try {//from ww w . j ava2s. c o m JsonElement markerList = parser.parse(jsonString); if (markerList.isJsonArray()) { JsonArray markerArray = markerList.getAsJsonArray(); Log.i(TAG, "It's a JsonArry: " + markerArray.toString()); for (JsonElement marker : markerArray) { boolean addOne = true; // now we have marker if (marker.isJsonObject()) { JsonObject markerJson = marker.getAsJsonObject(); if (markerJson.get("lat") == null || markerJson.get("lng") == null) { addOne = false; } else { // having correct syntax of a marker in Json // check for cases: "lat" : "40.7561" (as String) JsonPrimitive jpLat = (JsonPrimitive) markerJson.get("lat"); JsonPrimitive jpLng = (JsonPrimitive) markerJson.get("lng"); double latitude = 0; double longitude = 0; try { //it's possible that when converting to Double, we will have errors // for example, some json has "lat": "" (empty string for lat, lng values) if (jpLat.isString() && jpLng.isString()) { Log.i(TAG, "jpLat:" + jpLat.toString()); Log.i(TAG, "jpLng:" + jpLng.toString()); latitude = new Double(jpLat.getAsString()); longitude = new Double(jpLng.getAsString()); Log.i(TAG, "convert to double:" + latitude + "," + longitude); } else { latitude = markerJson.get("lat").getAsDouble(); longitude = markerJson.get("lng").getAsDouble(); } } catch (NumberFormatException e) { addOne = false; } // check for Lat, Lng correct range if ((latitude < -90) || (latitude > 90) || (longitude < -180) || (longitude > 180)) { Log.i(TAG, "Lat/Lng wrong range:" + latitude + "," + longitude); addOne = false; } Color.colorToHSV(mMarkerColor, hsv); float defaultColor = hsv[0]; float color = (markerJson.get("color") == null) ? defaultColor : markerJson.get("color").getAsInt(); if ((color < 0) || (color > 360)) { Log.i(TAG, "Wrong color"); addOne = false; } String title = (markerJson.get("title") == null) ? "" : markerJson.get("title").getAsString(); String snippet = (markerJson.get("snippet") == null) ? "" : markerJson.get("snippet").getAsString(); boolean draggable = (markerJson.get("draggable") == null) ? mMarkerDraggable : markerJson.get("draggable").getAsBoolean(); if (addOne) { Log.i(TAG, "Adding marker" + latitude + "," + longitude); int uniqueId = generateMarkerId(); markerIds.add(uniqueId); addMarkerToMap(latitude, longitude, uniqueId, color, title, snippet, draggable); } } } } //end of JsonArray } else { // not a JsonArray form.dispatchErrorOccurredEvent(this, "AddMarkersFromJson", ErrorMessages.ERROR_GOOGLE_MAP_INVALID_INPUT, "markers needs to be represented as JsonArray"); markersList = YailList.makeList(markerIds); } } catch (JsonSyntaxException e) { form.dispatchErrorOccurredEvent(this, "AddMarkersFromJson", ErrorMessages.ERROR_GOOGLE_MAP_JSON_FORMAT_DECODE_FAILED, jsonString); markersList = YailList.makeList(markerIds); // return an empty markerIds list } markersList = YailList.makeList(markerIds); // return YailList.makeList(markerIds); }
From source file:com.google.dart.server.internal.remote.RemoteAnalysisServerImpl.java
License:Open Source License
private void processResponse(JsonObject response) throws Exception { // handle notification if (processNotification(response)) { return;//from w w w.j a v a2s . co m } // prepare ID JsonPrimitive idJsonPrimitive = (JsonPrimitive) response.get("id"); if (idJsonPrimitive == null) { return; } String idString = idJsonPrimitive.getAsString(); // prepare consumer Consumer consumer; synchronized (consumerMapLock) { consumer = consumerMap.get(idString); } JsonObject errorObject = (JsonObject) response.get("error"); RequestError requestError = null; if (errorObject != null) { requestError = processErrorResponse(errorObject); listener.requestError(requestError); } // handle result JsonObject resultObject = (JsonObject) response.get("result"); // // Analysis Domain // if (consumer instanceof UpdateContentConsumer) { ((UpdateContentConsumer) consumer).onResponse(); } // // Completion Domain // if (consumer instanceof GetSuggestionsConsumer) { new CompletionIdProcessor((GetSuggestionsConsumer) consumer).process(resultObject, requestError); } // // Search Domain // else if (consumer instanceof FindElementReferencesConsumer) { new FindElementReferencesProcessor((FindElementReferencesConsumer) consumer).process(resultObject, requestError); } else if (consumer instanceof FindMemberDeclarationsConsumer) { new FindMemberDeclarationsProcessor((FindMemberDeclarationsConsumer) consumer).process(resultObject, requestError); } else if (consumer instanceof FindMemberReferencesConsumer) { new FindMemberReferencesProcessor((FindMemberReferencesConsumer) consumer).process(resultObject, requestError); } else if (consumer instanceof FindTopLevelDeclarationsConsumer) { new FindTopLevelDeclarationsProcessor((FindTopLevelDeclarationsConsumer) consumer).process(resultObject, requestError); } else if (consumer instanceof GetTypeHierarchyConsumer) { new TypeHierarchyProcessor((GetTypeHierarchyConsumer) consumer).process(resultObject, requestError); } // // Edit Domain // else if (consumer instanceof FormatConsumer) { new FormatProcessor((FormatConsumer) consumer).process(resultObject, requestError); } else if (consumer instanceof GetHoverConsumer) { new HoverProcessor((GetHoverConsumer) consumer).process(resultObject, requestError); } else if (consumer instanceof GetRefactoringConsumer) { new GetRefactoringProcessor(requestToRefactoringKindMap, (GetRefactoringConsumer) consumer) .process(idString, resultObject, requestError); } else if (consumer instanceof GetAssistsConsumer) { new AssistsProcessor((GetAssistsConsumer) consumer).process(resultObject, requestError); } else if (consumer instanceof GetFixesConsumer) { new FixesProcessor((GetFixesConsumer) consumer).process(resultObject, requestError); } else if (consumer instanceof GetLibraryDependenciesConsumer) { new LibraryDependenciesProcessor((GetLibraryDependenciesConsumer) consumer).process(resultObject, requestError); } else if (consumer instanceof GetNavigationConsumer) { new GetNavigationProcessor((GetNavigationConsumer) consumer).process(resultObject, requestError); } else if (consumer instanceof GetAvailableRefactoringsConsumer) { new RefactoringGetAvailableProcessor((GetAvailableRefactoringsConsumer) consumer).process(resultObject, requestError); } else if (consumer instanceof GetErrorsConsumer) { new AnalysisErrorsProcessor((GetErrorsConsumer) consumer).process(resultObject, requestError); } else if (consumer instanceof OrganizeDirectivesConsumer) { new OrganizeDirectivesProcessor((OrganizeDirectivesConsumer) consumer).process(resultObject, requestError); } else if (consumer instanceof SortMembersConsumer) { new SortMembersProcessor((SortMembersConsumer) consumer).process(resultObject, requestError); } // // Execution Domain // else if (consumer instanceof CreateContextConsumer) { new CreateContextProcessor((CreateContextConsumer) consumer).process(resultObject, requestError); } else if (consumer instanceof MapUriConsumer) { new MapUriProcessor((MapUriConsumer) consumer).process(resultObject, requestError); } // // Server Domain // else if (consumer instanceof GetVersionConsumer) { new VersionProcessor((GetVersionConsumer) consumer).process(resultObject, requestError); } else if (consumer instanceof BasicConsumer) { ((BasicConsumer) consumer).received(); } synchronized (consumerMapLock) { consumerMap.remove(idString); } }
From source file:com.google.devtools.kythe.platform.shared.KytheMetadataLoader.java
License:Open Source License
@Nullable private static RuleXorError parseRule(JsonObject json) { JsonPrimitive ruleType = json.getAsJsonPrimitive(TYPE); if (ruleType == null) { return RuleXorError.create("Rule missing type."); }//from ww w. j a v a 2 s .c om switch (ruleType.getAsString()) { case NOP: return null; case ANCHOR_DEFINES: Metadata.Rule rule = new Metadata.Rule(); rule.vname = GSON.fromJson(json.getAsJsonObject(VNAME), VName.class); rule.begin = json.getAsJsonPrimitive(BEGIN).getAsInt(); rule.end = json.getAsJsonPrimitive(END).getAsInt(); String edge = json.getAsJsonPrimitive(EDGE).getAsString(); if (edge.length() == 0) { return RuleXorError.create("Rule edge has zero length"); } rule.reverseEdge = (edge.charAt(0) == '%'); if (rule.reverseEdge) { edge = edge.substring(1); } if (edge.equals(GENERATES)) { rule.edgeOut = EdgeKind.GENERATES; } else { return RuleXorError.create("Unknown edge type: " + edge); } return RuleXorError.create(rule); default: return RuleXorError.create("Unknown rule type: " + ruleType.getAsString()); } }
From source file:com.google.devtools.kythe.platform.shared.KytheMetadataLoader.java
License:Open Source License
@Override public Metadata parseFile(String fileName, byte[] data) { if (!fileName.endsWith(META_SUFFIX)) { return null; }//from w w w .j a v a 2 s. co m JsonElement root = null; try (ByteArrayInputStream stream = new ByteArrayInputStream(data); InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) { root = PARSER.parse(reader); } catch (IOException ex) { emitWarning(ex.getMessage(), fileName); return null; } if (root == null || !root.isJsonObject()) { emitWarning("Missing root.", fileName); return null; } JsonObject rootObject = root.getAsJsonObject(); JsonPrimitive rootType = rootObject.getAsJsonPrimitive(TYPE); if (rootType == null || !rootType.getAsString().equals(KYTHE_FORMAT_0)) { emitWarning("Root missing type.", fileName); return null; } JsonArray rules = rootObject.getAsJsonArray(META); if (rules == null) { emitWarning("Root missing meta array.", fileName); return null; } Metadata metadata = new Metadata(); for (JsonElement rule : rules) { RuleXorError ruleXorError = parseRule(rule.getAsJsonObject()); if (ruleXorError != null) { // skip nulls Metadata.Rule metadataRule = ruleXorError.rule(); if (metadataRule != null) { metadata.addRule(metadataRule); } else { emitWarning(ruleXorError.error(), fileName); } } } return metadata; }
From source file:com.google.gms.googleservices.GoogleServicesTask.java
License:Apache License
/** * Handle project_info/project_number for @string/gcm_defaultSenderId, and fill the res map with the read value. * @param rootObject the root Json object. * @throws IOException/*from w w w . j a v a 2 s .c o m*/ */ private void handleProjectNumber(JsonObject rootObject, Map<String, String> resValues) throws IOException { JsonObject projectInfo = rootObject.getAsJsonObject("project_info"); if (projectInfo == null) { throw new GradleException("Missing project_info object"); } JsonPrimitive projectNumber = projectInfo.getAsJsonPrimitive("project_number"); if (projectNumber == null) { throw new GradleException("Missing project_info/project_number object"); } resValues.put("gcm_defaultSenderId", projectNumber.getAsString()); }
From source file:com.google.gms.googleservices.GoogleServicesTask.java
License:Apache License
/** * Handle a client object for analytics (@xml/global_tracker) * @param clientObject the client Json object. * @throws IOException/*from w w w . j a v a 2 s . com*/ */ private void handleAnalytics(JsonObject clientObject, Map<String, String> resValues) throws IOException { JsonObject analyticsService = getServiceByName(clientObject, "analytics_service"); if (analyticsService == null) return; JsonObject analyticsProp = analyticsService.getAsJsonObject("analytics_property"); if (analyticsProp == null) return; JsonPrimitive trackingId = analyticsProp.getAsJsonPrimitive("tracking_id"); if (trackingId == null) return; resValues.put("ga_trackingId", trackingId.getAsString()); File xml = new File(intermediateDir, "xml"); if (!xml.exists() && !xml.mkdirs()) { throw new GradleException("Failed to create folder: " + xml); } Files.write(getGlobalTrackerContent(trackingId.getAsString()), new File(xml, "global_tracker.xml"), Charsets.UTF_8); }
From source file:com.google.gms.googleservices.GoogleServicesTask.java
License:Apache License
private static void findStringByName(JsonObject jsonObject, String stringName, Map<String, String> resValues) { JsonPrimitive id = jsonObject.getAsJsonPrimitive(stringName); if (id != null) { resValues.put(stringName, id.getAsString()); }/* w w w.jav a2 s . c o m*/ }
From source file:com.google.gms.googleservices.GoogleServicesTask.java
License:Apache License
/** * find an item in the "client" array that match the package name of the app * @param jsonObject the root json object. * @return a JsonObject representing the client entry or null if no match is found. *//*from ww w . jav a 2 s .co m*/ private JsonObject getClientForPackageName(JsonObject jsonObject) { JsonArray array = jsonObject.getAsJsonArray("client"); if (array != null) { final int count = array.size(); for (int i = 0; i < count; i++) { JsonElement clientElement = array.get(i); if (clientElement == null || !clientElement.isJsonObject()) { continue; } JsonObject clientObject = clientElement.getAsJsonObject(); JsonObject clientInfo = clientObject.getAsJsonObject("client_info"); if (clientInfo == null) continue; JsonObject androidClientInfo = clientInfo.getAsJsonObject("android_client_info"); if (androidClientInfo == null) continue; JsonPrimitive clientPackageName = androidClientInfo.getAsJsonPrimitive("package_name"); if (clientPackageName == null) continue; if (packageName.equals(clientPackageName.getAsString())) { return clientObject; } } } return null; }