List of usage examples for org.json JSONArray getString
public String getString(int index) throws JSONException
From source file:de.hscoburg.etif.vbis.lagerix.android.barcode.result.supplement.BookResultInfoRetriever.java
@Override void retrieveSupplementalInfo() throws IOException { CharSequence contents = HttpHelper.downloadViaHttp( "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn, HttpHelper.ContentType.JSON); if (contents.length() == 0) { return;/*from w w w. j a v a2 s . com*/ } String title; String pages; Collection<String> authors = null; try { JSONObject topLevel = (JSONObject) new JSONTokener(contents.toString()).nextValue(); JSONArray items = topLevel.optJSONArray("items"); if (items == null || items.isNull(0)) { return; } JSONObject volumeInfo = ((JSONObject) items.get(0)).getJSONObject("volumeInfo"); if (volumeInfo == null) { return; } title = volumeInfo.optString("title"); pages = volumeInfo.optString("pageCount"); JSONArray authorsArray = volumeInfo.optJSONArray("authors"); if (authorsArray != null && !authorsArray.isNull(0)) { authors = new ArrayList<String>(authorsArray.length()); for (int i = 0; i < authorsArray.length(); i++) { authors.add(authorsArray.getString(i)); } } } catch (JSONException e) { throw new IOException(e.toString()); } Collection<String> newTexts = new ArrayList<String>(); maybeAddText(title, newTexts); maybeAddTextSeries(authors, newTexts); maybeAddText(pages == null || pages.length() == 0 ? null : pages + "pp.", newTexts); String baseBookUri = "http://www.google." + LocaleManager.getBookSearchCountryTLD(context) + "/search?tbm=bks&source=zxing&q="; append(isbn, source, newTexts.toArray(new String[newTexts.size()]), baseBookUri + isbn); }
From source file:com.github.stephanarts.cas.ticket.registry.RegistryClient.java
/** * Get a ticket from the ticketregistry. * * @return Ticket Objects/*from w ww . j a v a 2 s .c o m*/ * * @throws JSONRPCException Throws JSONRPCException containing any error. */ public final Collection<Ticket> getTickets() throws JSONRPCException { JSONObject params = new JSONObject(); JSONObject result; JSONArray resultTickets; Ticket ticket; ArrayList<Ticket> tickets = new ArrayList<Ticket>(); result = this.call("cas.getTickets", params); if (result.has("tickets")) { logger.debug("Number of Tickets: " + result.getJSONArray("tickets").length()); resultTickets = result.getJSONArray("tickets"); for (int i = 0; i < resultTickets.length(); ++i) { try { String serializedTicket = resultTickets.getString(i); ByteArrayInputStream bi = new ByteArrayInputStream( DatatypeConverter.parseBase64Binary(serializedTicket)); ObjectInputStream si = new ObjectInputStream(bi); ticket = (Ticket) si.readObject(); tickets.add(ticket); } catch (final Exception e) { throw new JSONRPCException(-32501, "Could not decode Ticket"); } } } return tickets; }
From source file:org.ESLM.Parser.ExerciseFactory.java
private static String[] createAnswers(JSONArray JSONAnswers) { int numberOfAnswers = JSONAnswers.length(); String[] answers = new String[numberOfAnswers]; for (int i = 0; i < numberOfAnswers; i++) { answers[i] = JSONAnswers.getString(i); }/*w ww.ja v a 2 s . co m*/ return answers; }
From source file:org.qi4j.entitystore.sql.SQLEntityStoreMixin.java
private Map<QualifiedName, List<EntityReference>> createManyAssociations(JSONObject jsonObject, EntityDescriptor entityDescriptor) throws JSONException { JSONObject manyAssocs = jsonObject.getJSONObject("manyassociations"); Map<QualifiedName, List<EntityReference>> manyAssociations = new HashMap<QualifiedName, List<EntityReference>>(); for (AssociationDescriptor manyAssociationType : entityDescriptor.state().manyAssociations()) { List<EntityReference> references = new ArrayList<EntityReference>(); try {/*from w w w . ja va2 s . c om*/ JSONArray jsonValues = manyAssocs.getJSONArray(manyAssociationType.qualifiedName().name()); for (int i = 0; i < jsonValues.length(); i++) { Object jsonValue = jsonValues.getString(i); EntityReference value = jsonValue == JSONObject.NULL ? null : EntityReference.parseEntityReference((String) jsonValue); references.add(value); } manyAssociations.put(manyAssociationType.qualifiedName(), references); } catch (JSONException e) { // ManyAssociation not found, default to empty one manyAssociations.put(manyAssociationType.qualifiedName(), references); } } return manyAssociations; }
From source file:com.polychrom.cordova.ActionBarPlugin.java
@Override public boolean execute(final String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException { if (!plugin_actions.contains(action)) { return false; }//from w w w . ja v a2 s . c o m final Activity ctx = (Activity) cordova; if ("isAvailable".equals(action)) { JSONObject result = new JSONObject(); result.put("value", ctx.getWindow().hasFeature(Window.FEATURE_ACTION_BAR)); callbackContext.success(result); return true; } final ActionBar bar = ctx.getActionBar(); if (bar == null) { Window window = ctx.getWindow(); if (!window.hasFeature(Window.FEATURE_ACTION_BAR)) { callbackContext .error("ActionBar feature not available, Window.FEATURE_ACTION_BAR must be enabled!"); } else { callbackContext.error("Failed to get ActionBar"); } return true; } if (menu == null) { callbackContext.error("Options menu not initialised"); return true; } final StringBuffer error = new StringBuffer(); JSONObject result = new JSONObject(); if ("isShowing".equals(action)) { result.put("value", bar.isShowing()); } else if ("getHeight".equals(action)) { result.put("value", bar.getHeight()); } else if ("getDisplayOptions".equals(action)) { result.put("value", bar.getDisplayOptions()); } else if ("getNavigationMode".equals(action)) { result.put("value", bar.getNavigationMode()); } else if ("getSelectedNavigationItem".equals(action)) { result.put("value", bar.getSelectedNavigationIndex()); } else if ("getSubtitle".equals(action)) { result.put("value", bar.getSubtitle()); } else if ("getTitle".equals(action)) { result.put("value", bar.getTitle()); } else { try { JSONException exception = new Runnable() { public JSONException exception = null; public void run() { try { // This is a bit of a hack (should be specific to the request, not global) bases = new String[] { removeFilename(webView.getOriginalUrl()), removeFilename(webView.getUrl()) }; if ("show".equals(action)) { bar.show(); } else if ("hide".equals(action)) { bar.hide(); } else if ("setMenu".equals(action)) { if (args.isNull(0)) { error.append("menu can not be null"); return; } menu_definition = args.getJSONArray(0); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { ctx.invalidateOptionsMenu(); } } else if ("setTabs".equals(action)) { if (args.isNull(0)) { error.append("menu can not be null"); return; } bar.removeAllTabs(); tab_callbacks.clear(); if (!buildTabs(bar, args.getJSONArray(0))) { error.append("Invalid tab bar definition"); } } else if ("setDisplayHomeAsUpEnabled".equals(action)) { if (args.isNull(0)) { error.append("showHomeAsUp can not be null"); return; } bar.setDisplayHomeAsUpEnabled(args.getBoolean(0)); } else if ("setDisplayOptions".equals(action)) { if (args.isNull(0)) { error.append("options can not be null"); return; } final int options = args.getInt(0); bar.setDisplayOptions(options); } else if ("setDisplayShowHomeEnabled".equals(action)) { if (args.isNull(0)) { error.append("showHome can not be null"); return; } bar.setDisplayShowHomeEnabled(args.getBoolean(0)); } else if ("setDisplayShowTitleEnabled".equals(action)) { if (args.isNull(0)) { error.append("showTitle can not be null"); return; } bar.setDisplayShowTitleEnabled(args.getBoolean(0)); } else if ("setDisplayUseLogoEnabled".equals(action)) { if (args.isNull(0)) { error.append("useLogo can not be null"); return; } bar.setDisplayUseLogoEnabled(args.getBoolean(0)); } else if ("setHomeButtonEnabled".equals(action)) { if (args.isNull(0)) { error.append("enabled can not be null"); return; } bar.setHomeButtonEnabled(args.getBoolean(0)); } else if ("setIcon".equals(action)) { if (args.isNull(0)) { error.append("icon can not be null"); return; } Drawable drawable = getDrawableForURI(args.getString(0)); bar.setIcon(drawable); } else if ("setListNavigation".equals(action)) { JSONArray items = null; if (args.isNull(0) == false) { items = args.getJSONArray(0); } navigation_adapter.setItems(items); bar.setListNavigationCallbacks(navigation_adapter, navigation_listener); } else if ("setLogo".equals(action)) { if (args.isNull(0)) { error.append("logo can not be null"); return; } Drawable drawable = getDrawableForURI(args.getString(0)); bar.setLogo(drawable); } else if ("setNavigationMode".equals(action)) { if (args.isNull(0)) { error.append("mode can not be null"); return; } final int mode = args.getInt(0); bar.setNavigationMode(mode); } else if ("setSelectedNavigationItem".equals(action)) { if (args.isNull(0)) { error.append("position can not be null"); return; } bar.setSelectedNavigationItem(args.getInt(0)); } else if ("setSubtitle".equals(action)) { if (args.isNull(0)) { error.append("subtitle can not be null"); return; } bar.setSubtitle(args.getString(0)); } else if ("setTitle".equals(action)) { if (args.isNull(0)) { error.append("title can not be null"); return; } bar.setTitle(args.getString(0)); } } catch (JSONException e) { exception = e; } finally { synchronized (this) { this.notify(); } } } // Run task synchronously { synchronized (this) { ctx.runOnUiThread(this); this.wait(); } } }.exception; if (exception != null) { throw exception; } } catch (InterruptedException e) { error.append("Function interrupted on UI thread"); } } if (error.length() == 0) { if (result.length() > 0) { callbackContext.success(result); } else { callbackContext.success(); } } else { callbackContext.error(error.toString()); } return true; }
From source file:menusearch.json.JSONProcessor.java
/** * //from w w w . ja va2 s .c o m * @param json formated JSON string containing all the information for one recipe * @return Recipe object * @throws IOException * * This method takes a formated json string containing one recipe, parses it, and saves it into a recipe object which is then returned. * **You must call the getRecipeAPI() method prior to calling this method. */ public static Recipe parseRecipe(String json) throws IOException, JSONException { JSONTokener tokenizer = new JSONTokener(json); JSONObject obj = new JSONObject(tokenizer); Recipe r = new Recipe(); JSONObject attribution = obj.getJSONObject("attribution"); Attribution a = new Attribution(); a.setHTML(attribution.getString("html")); a.setUrl(attribution.getString("url")); a.setText(attribution.getString("text")); a.setLogo(attribution.getString("logo")); r.setAttribution(a); JSONArray ingredientList = obj.getJSONArray("ingredientLines"); for (int i = 0; i < ingredientList.length(); i++) { r.addIngredient(ingredientList.getString(i)); } JSONObject flavors = obj.getJSONObject("flavors"); r.setBitterFlavor(flavors.getDouble("Bitter")); r.setMeatyFlavor(flavors.getDouble("Meaty")); r.setPiquantFlavor(flavors.getDouble("Piquant")); r.setSaltyFlavor(flavors.getDouble("Salty")); r.setSourFlavor(flavors.getDouble("Sour")); r.setSweetFlavor(flavors.getDouble("Sweet")); JSONArray nutritionEstimates = obj.getJSONArray("nutritionEstimates"); for (int i = 0; i < nutritionEstimates.length(); i++) { NutritionEstimate nutritionInfo = new NutritionEstimate(); Unit aUnit = new Unit(); JSONObject nutrition = nutritionEstimates.getJSONObject(i); nutritionInfo.setAttribute(nutrition.getString("attribute")); if (nutrition.isNull("description") != true) nutritionInfo.setDescription(nutrition.getString("description")); nutritionInfo.setValue(nutrition.getDouble("value")); JSONObject unit = nutrition.getJSONObject("unit"); aUnit.setAbbreviation(unit.getString("abbreviation")); aUnit.setName(unit.getString("name")); aUnit.setPlural(unit.getString("plural")); aUnit.setPluralAbbreviation(unit.getString("pluralAbbreviation")); nutritionInfo.addUnit(aUnit); r.addNutritionInfo(nutritionInfo); } JSONArray images = obj.getJSONArray("images"); JSONObject imageBySize = images.getJSONObject(0); for (int i = 0; i < images.length(); i++) { if (images.getJSONObject(i).has("hostedLargeUrl")) r.setHostedlargeUrl(images.getJSONObject(i).getString("hostedLargeUrl")); if (images.getJSONObject(i).has("hostedMediumUrl")) r.setHostedMediumUrl(images.getJSONObject(i).getString("hostedMediumUrl")); if (images.getJSONObject(i).has("hostedSmallUrl")) r.setHostedSmallUrl(images.getJSONObject(i).getString("hostedSmallUrl")); } if (obj.has("name")) r.setName(obj.getString("name")); if (obj.has("yield")) r.setYield(obj.getString("yield")); if (obj.has("totalTime")) r.setTotalTime(obj.getString("totalTime")); if (obj.has("attributes")) { JSONObject attributes = obj.getJSONObject("attributes"); if (attributes.has("holiday")) { JSONArray holidays = attributes.getJSONArray("holiday"); for (int i = 0; i < holidays.length(); i++) { r.addholidayToList(holidays.getString(i)); } } if (attributes.has("cuisine")) { JSONArray cuisine = attributes.getJSONArray("cuisine"); for (int i = 0; i < cuisine.length(); i++) { r.addCuisineToList(cuisine.getString(i)); } } } if (obj.has("totalTimeInSeconds")) r.setTimetoCook(obj.getDouble("totalTimeInSeconds")); if (obj.has("rating")) r.setRating(obj.getDouble("rating")); if (obj.has("numberofServings")) r.setNumberOfServings(obj.getDouble("numberOfServings")); if (obj.has("source")) { JSONObject source = obj.getJSONObject("source"); if (source.has("sourceSiteUrl")) r.setSourceSiteUrl(source.getString("sourceSiteUrl")); if (source.has("sourceRecipeUrl")) r.setSourceRecipeUrl(source.getString("sourceRecipeUrl")); if (source.has("sourceDisplayName")) r.setSourceDisplayName(source.getString("sourceDisplayName")); } r.setRecipeID(obj.getString("id")); return r; }
From source file:menusearch.json.JSONProcessor.java
/** *//from w w w.j ava2 s . com * @param JSON string: requires the JSON string of the parameters the user enter for the search * @return RecipeSummaryList: a RecipeSummaryList where it contains information about the recipes that matches the search the user made * @throws java.io.IOException */ public static RecipeSummaryList parseRecipeMatches(String results) throws IOException { CourseList courseList = new CourseList(); RecipeSummaryList list = new RecipeSummaryList(); JSONTokener tokenizer = new JSONTokener(results); JSONObject resultList = new JSONObject(tokenizer); JSONArray matches = resultList.getJSONArray("matches"); for (int i = 0; i < matches.length(); i++) { RecipeSummary r = new RecipeSummary(); JSONObject currentRecipe = matches.getJSONObject(i); JSONObject imageUrls = currentRecipe.getJSONObject("imageUrlsBySize"); String link = "90"; String number = imageUrls.getString(link); r.setImageUrlsBySize(number); String source = (String) currentRecipe.getString("sourceDisplayName"); r.setSourceDisplayName(source); JSONArray listOfIngredients = currentRecipe.getJSONArray("ingredients"); for (int n = 0; n < listOfIngredients.length(); n++) { String currentIngredients = listOfIngredients.getString(n); r.ingredients.add(currentIngredients); } String id = (String) currentRecipe.getString("id"); r.setId(id); String recipe = (String) currentRecipe.get("recipeName"); r.setRecipeName(recipe); JSONArray smallImage = currentRecipe.getJSONArray("smallImageUrls"); for (int l = 0; l < smallImage.length(); l++) { String currentUrl = (String) smallImage.get(l); r.setSmallImageUrls(currentUrl); } int timeInSeconds = (int) currentRecipe.getInt("totalTimeInSeconds"); r.setTotalTimeInSeconds(timeInSeconds); String a = "attributes"; String c = "course"; if (currentRecipe.has(a)) { JSONObject currentAttributes = currentRecipe.getJSONObject(a); if (currentAttributes.has(c)) { for (int j = 0; j < currentAttributes.getJSONArray(c).length(); j++) { String course = currentAttributes.getJSONArray(c).getString(j); courseList.add(course); } r.setCourses(courseList); } } CuisineList cuisineList = new CuisineList(); if (currentRecipe.has(a)) { JSONObject currentAttributes = currentRecipe.getJSONObject(a); if (currentAttributes.has("cuisine")) { for (int j = 0; j < currentAttributes.getJSONArray("cuisine").length(); j++) { String currentCuisine = currentAttributes.getJSONArray("cuisine").getString(j); cuisineList.add(currentCuisine); } r.setCusines(cuisineList); } } String f = "flavors"; JSONObject currentFlavors; if (currentRecipe.has(f) == true) { if (currentRecipe.isNull(f) == false) { currentFlavors = currentRecipe.getJSONObject(f); double saltyRating = currentFlavors.getDouble("salty"); double sourRating = currentFlavors.getDouble("sour"); double sweetRating = currentFlavors.getDouble("sweet"); double bitterRating = currentFlavors.getDouble("bitter"); double meatyRating = currentFlavors.getDouble("meaty"); double piguantRating = currentFlavors.getDouble("piquant"); r.flavors.setSalty(saltyRating); r.flavors.setSour(sourRating); r.flavors.setSweet(sweetRating); r.flavors.setBitter(bitterRating); r.flavors.setMeaty(meatyRating); r.flavors.setPiquant(piguantRating); } if (currentRecipe.get(f) == null) { r.flavors = null; } if (currentRecipe.get(f) == null) r.flavors = null; } double rate = currentRecipe.getInt("rating"); r.setRating(rate); list.matches.add(i, r); } return list; }
From source file:com.phonegap.plugins.statusBarNotification.StatusBarNotification.java
/** * Executes the request and returns PluginResult * * @param action Action to execute * @param data JSONArray of arguments to the plugin * @param callbackContext The callback context used when calling back into JavaScript. * * @return A PluginRequest object with a status * *///from w ww .ja v a 2s . c o m @Override public boolean execute(String action, JSONArray data, CallbackContext callbackContext) { boolean actionValid = true; if (NOTIFY.equals(action)) { try { String tag = data.getString(0); String title = data.getString(1); String body = data.getString(2); String flag = data.getString(3); Log.d("NotificationPlugin", "Notification: " + tag + ", " + title + ", " + body); int notificationFlag = getFlagValue(flag); showNotification(tag, title, body, notificationFlag); } catch (JSONException jsonEx) { Log.d("NotificationPlugin", "Got JSON Exception " + jsonEx.getMessage()); actionValid = false; } } else if (CLEAR.equals(action)) { try { String tag = data.getString(0); Log.d("NotificationPlugin", "Notification cancel: " + tag); clearNotification(tag); } catch (JSONException jsonEx) { Log.d("NotificationPlugin", "Got JSON Exception " + jsonEx.getMessage()); actionValid = false; } } else { actionValid = false; Log.d("NotificationPlugin", "Invalid action : " + action + " passed"); } return actionValid; }
From source file:com.ibm.mobilefirstplatform.clientsdk.cordovaplugins.push.CDVMFPPush.java
@Override public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException { pushLogger.debug("execute() : action = " + action); if ("registerDevice".equals(action)) { this.registerDevice(callbackContext); return true; } else if ("unregisterDevice".equals(action)) { this.unregisterDevice(callbackContext); return true; } else if ("retrieveSubscriptions".equals(action)) { this.retrieveSubscriptions(callbackContext); return true; } else if ("retrieveAvailableTags".equals(action)) { this.retrieveAvailableTags(callbackContext); return true; } else if ("subscribe".equals(action)) { String tag = args.getString(0); this.subscribe(tag, callbackContext); return true; } else if ("unsubscribe".equals(action)) { String tag = args.getString(0); this.unsubscribe(tag, callbackContext); return true; } else if ("registerNotificationsCallback".equals(action)) { this.registerNotificationsCallback(callbackContext); return true; }/*from w ww . j a v a2 s . co m*/ return false; }
From source file:de.kp.ames.web.core.json.JsonUtil.java
/** * A helper method to retrieve Array-based attribute * values from the provided JSONObject// w w w .j av a 2 s . co m * * @param key * @param jObject * @return * @throws JSONException */ public static ArrayList<String> getAttributeAsArray(String key, JSONObject jObject) throws JSONException { ArrayList<String> values = null; if (jObject.has(key)) { /* * Retrieve json array from in more fault tolerant manner */ JSONArray jArray = getJArray(key, jObject); if (jArray.length() > 0) { values = new ArrayList<String>(); for (int i = 0; i < jArray.length(); i++) { values.add(jArray.getString(i)); } } } return values; }