List of usage examples for org.json JSONObject keys
public Iterator keys()
From source file:com.inductiveautomation.reporting.examples.datasource.common.RestJsonDataSource.java
/** * Looks through the {@link JSONArray}, evaluating each {@link JSONObject} to determine which has the largest * set of keys. This process is useful because not all JSON objects in an array may have the same key set. There * are some assumptions made that the largest keyset will contain all the keys available in those of lower sets. * This is far from true, but this assumption is allowed for the sake of simplicity for this example. * @param jsonArray a {@link JSONArray}//from ww w . j a va2 s .co m * @return a JSONObject containing the most keys found in the array. May be empty. */ private JSONObject findReferenceObjectIndex(JSONArray jsonArray) throws JSONException { JSONObject reference = null; if (jsonArray != null && jsonArray.length() > 0) { reference = jsonArray.getJSONObject(0); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jo = jsonArray.getJSONObject(i); if (Iterators.size(jo.keys()) > Iterators.size(reference.keys())) { reference = jo; } } } return reference == null ? new JSONObject() : reference; }
From source file:com.inductiveautomation.reporting.examples.datasource.common.RestJsonDataSource.java
/** * Creates and returns {@link Dataset} with String column types from a {@link JSONArray}. Returns empty if no data * was found and an exception was not thrown. */// www . j a v a 2 s .c o m private Dataset createDatasetFromJSONArray(JSONArray jsonArray) throws JSONException { Dataset ds = null; if (jsonArray.length() >= 1) { // JSON objects in an array may not have values for each key, so make sure we // get the full keyset JSONObject reference = findReferenceObjectIndex(jsonArray); // get column names from the reference object List<String> colNames = new ArrayList<>(); Iterator keys = reference.keys(); while (keys.hasNext()) { colNames.add(keys.next().toString()); } // now start building dataset to pass into report engine DatasetBuilder builder = new DatasetBuilder(); builder.colNames(colNames.toArray(new String[colNames.size()])); // set the column types. We're using all strings in this example, but we could be // checking for numeric types and setting different column types to enable calculations Class[] types = new Class[colNames.size()]; for (int i = 0; i < types.length; i++) { types[i] = String.class; } builder.colTypes(types); // now create rows for each json list value for (int row = 0; row < jsonArray.length(); row++) { String[] rowData = new String[colNames.size()]; for (int col = 0; col < colNames.size(); col++) { try { rowData[col] = jsonArray.getJSONObject(row).get(colNames.get(col)).toString(); } catch (JSONException e) { // ignore because it just means this object didn't have our key } } builder.addRow(rowData); } ds = builder.build(); } return ds != null ? ds : new BasicDataset(); }
From source file:org.loklak.server.Accounting.java
/** * cleanup deletes all old entries and frees up the memory. * some outside process muss call this frequently * @return self/*from w ww . j av a2 s . c o m*/ */ public Accounting cleanup() { if (!this.has("requests")) return this; JSONObject requests = this.getJSONObject("requests"); for (String path : requests.keySet()) { JSONObject events = requests.getJSONObject(path); // shrink that map and delete everything which is older than now minus one hour long pivotTime = System.currentTimeMillis() - ONE_HOUR_MILLIS; while (events.length() > 0 && Long.parseLong(events.keys().next()) < pivotTime) events.remove(events.keys().next()); if (events.length() == 0) requests.remove(path); } return this; }
From source file:de.grobox.blitzmail.MainActivity.java
private void sendNow() { JSONObject mails = MailStorage.getMails(this); Iterator<?> i = mails.keys(); while (i.hasNext()) { String mail = mails.opt((String) i.next()).toString(); Intent intent = new Intent(this, SendActivity.class); intent.setAction("BlitzMailReSend"); intent.putExtra("mail", mail); startActivity(intent);/*from w w w. j ava2 s .c o m*/ } ((PreferenceCategory) findPreference("pref_sending")).removePreference(findPreference("pref_send_now")); }
From source file:de.schildbach.wallet.ExchangeRatesProvider.java
private static Map<String, ExchangeRate> requestExchangeRates(final URL url, final String userAgent, final String source, final String... fields) { final long start = System.currentTimeMillis(); HttpURLConnection connection = null; Reader reader = null;/*from w w w. j a va 2 s .c o m*/ try { connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS); connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS); connection.addRequestProperty("User-Agent", userAgent); connection.addRequestProperty("Accept-Encoding", "gzip"); connection.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { final String contentEncoding = connection.getContentEncoding(); InputStream is = new BufferedInputStream(connection.getInputStream(), 1024); if ("gzip".equalsIgnoreCase(contentEncoding)) is = new GZIPInputStream(is); reader = new InputStreamReader(is, Charsets.UTF_8); final StringBuilder content = new StringBuilder(); final long length = Io.copy(reader, content); final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); final JSONObject head = new JSONObject(content.toString()); for (final Iterator<String> i = head.keys(); i.hasNext();) { final String currencyCode = i.next(); if (!"timestamp".equals(currencyCode)) { final JSONObject o = head.getJSONObject(currencyCode); for (final String field : fields) { final String rateStr = o.optString(field, null); if (rateStr != null) { try { final Fiat rate = Fiat.parseFiat(currencyCode, rateStr); if (rate.signum() > 0) { rates.put(currencyCode, new ExchangeRate( new org.bitcoinj.utils.ExchangeRate(rate), source)); break; } } catch (final NumberFormatException x) { log.warn("problem fetching {} exchange rate from {} ({}): {}", currencyCode, url, contentEncoding, x.getMessage()); } } } } } log.info("fetched exchange rates from {} ({}), {} chars, took {} ms", url, contentEncoding, length, System.currentTimeMillis() - start); return rates; } else { log.warn("http status {} when fetching exchange rates from {}", responseCode, url); } } catch (final Exception x) { log.warn("problem fetching exchange rates from " + url, x); } finally { if (reader != null) { try { reader.close(); } catch (final IOException x) { // swallow } } if (connection != null) connection.disconnect(); } return null; }
From source file:org.cgiar.ilri.odk.pull.backend.services.FetchFormDataService.java
/** * This method is called whenever the service is called. Note that the service might have * already been running when it was called * * @param intent The intent used to call the service *///from w w w . j av a2 s .com @Override protected void onHandleIntent(Intent intent) { formName = intent.getStringExtra(KEY_FORM_NAME); if (formName != null) { //fetch data on the form try { String jsonString = DataHandler.sendDataToServer(this, null, DataHandler.URI_FETCH_FORM_DATA + URLEncoder.encode(formName, "UTF-8")); if (jsonString != null) { try { JSONObject jsonObject = new JSONObject(jsonString); JSONObject fileData = jsonObject.getJSONObject("files"); Iterator<String> keys = fileData.keys(); String fetchedFilesString = ""; while (keys.hasNext()) { String currFileName = keys.next(); Log.d(TAG, "Processing " + currFileName); JSONArray currFileData = fileData.getJSONArray(currFileName); if (currFileName.equals(Form.DEFAULT_CSV_FILE_NAME)) { Log.d(TAG, "Treating " + currFileName + " like a itemset file"); Log.d(TAG, currFileName + " data = " + currFileData.toString()); String csv = getCSVString(currFileData); if (csv != null) { saveCSVInFile(currFileName + Form.SUFFIX_CSV, csv); fetchedFilesString = fetchedFilesString + "\n" + " - " + currFileName + Form.SUFFIX_CSV; } else { Log.w(TAG, Form.DEFAULT_CSV_FILE_NAME + " from the server is null. Unable to save this on the device"); Toast.makeText(FetchFormDataService.this, getResources().getText(R.string.unable_fetch_data_for) + " " + currFileName, Toast.LENGTH_LONG).show(); } } else { Log.d(TAG, "Treating " + currFileName + " like an external data file"); boolean dataDumped = saveDataInDb(currFileName, currFileData); String csv = getCSVString(currFileData); if (csv != null) { if (dataDumped) { saveCSVInFile(currFileName + Form.SUFFIX_CSV + Form.SUFFIX_IMPORTED, csv); fetchedFilesString = fetchedFilesString + "\n" + " - " + currFileName + Form.SUFFIX_DB; fetchedFilesString = fetchedFilesString + "\n" + " - " + currFileName + Form.SUFFIX_CSV + Form.SUFFIX_IMPORTED; } else { saveCSVInFile(currFileName + Form.SUFFIX_CSV, csv); fetchedFilesString = fetchedFilesString + "\n" + " - " + currFileName + Form.SUFFIX_CSV; } } else { Log.w(TAG, currFileName + " from the server is null. Unable to save this on the device"); Toast.makeText(FetchFormDataService.this, getResources().getText(R.string.unable_fetch_data_for) + " " + currFileName, Toast.LENGTH_LONG).show(); } } } DataHandler.updateFormLastUpdateTime(FetchFormDataService.this, formName); if (fetchedFilesString.length() > 0) {//only show the notification if at least one file updated updateNotification(formName, getString(R.string.fetched_data), getString(R.string.the_following_files_were_added) + fetchedFilesString); } } catch (JSONException e) { e.printStackTrace(); } } else { Log.e(TAG, "Data from server null. Something happened while trying to fetch csv for " + formName); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else { Log.w(TAG, "Form name from intent bundle was null, doing nothing"); } }
From source file:com.trk.aboutme.facebook.model.JsonUtil.java
static void jsonObjectClear(JSONObject jsonObject) { @SuppressWarnings("unchecked") Iterator<String> keys = (Iterator<String>) jsonObject.keys(); while (keys.hasNext()) { keys.next();/*from w ww . jav a 2 s. c o m*/ keys.remove(); } }
From source file:com.trk.aboutme.facebook.model.JsonUtil.java
static boolean jsonObjectContainsValue(JSONObject jsonObject, Object value) { @SuppressWarnings("unchecked") Iterator<String> keys = (Iterator<String>) jsonObject.keys(); while (keys.hasNext()) { Object thisValue = jsonObject.opt(keys.next()); if (thisValue != null && thisValue.equals(value)) { return true; }//from w ww .ja va 2 s . co m } return false; }
From source file:com.trk.aboutme.facebook.model.JsonUtil.java
static Set<Map.Entry<String, Object>> jsonObjectEntrySet(JSONObject jsonObject) { HashSet<Map.Entry<String, Object>> result = new HashSet<Map.Entry<String, Object>>(); @SuppressWarnings("unchecked") Iterator<String> keys = (Iterator<String>) jsonObject.keys(); while (keys.hasNext()) { String key = keys.next(); Object value = jsonObject.opt(key); result.add(new JSONObjectEntry(key, value)); }//from w w w. j av a 2s.c o m return result; }
From source file:com.trk.aboutme.facebook.model.JsonUtil.java
static Set<String> jsonObjectKeySet(JSONObject jsonObject) { HashSet<String> result = new HashSet<String>(); @SuppressWarnings("unchecked") Iterator<String> keys = (Iterator<String>) jsonObject.keys(); while (keys.hasNext()) { result.add(keys.next());/*from w w w . ja va 2 s .c o m*/ } return result; }