List of usage examples for org.json JSONObject keys
public Iterator keys()
From source file:com.cannabiscoin.wallet.ExchangeRatesProvider.java
private static Map<String, ExchangeRate> requestExchangeRates(final URL url, final String userAgent, final String... fields) { final long start = System.currentTimeMillis(); HttpURLConnection connection = null; Reader reader = null;/*from ww w. jav a 2s . c om*/ try { Double btcRate = 0.0; boolean cryptsyValue = true; Object result = getCoinValueBTC(); if (result == null) { result = getCoinValueBTC_BTER(); cryptsyValue = false; if (result == null) return null; } btcRate = (Double) result; 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.connect(); final int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024), Constants.UTF_8); final StringBuilder content = new StringBuilder(); 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) { String rateStr = o.optString(field, null); if (rateStr != null) { try { double rateForBTC = Double.parseDouble(rateStr); rateStr = String.format("%.8f", rateForBTC * btcRate).replace(",", "."); final BigInteger rate = GenericUtils.toNanoCoins(rateStr, 0); if (rate.signum() > 0) { rates.put(currencyCode, new ExchangeRate(currencyCode, rate, url.getHost())); break; } } catch (final ArithmeticException x) { log.warn("problem fetching {} exchange rate from {}: {}", new Object[] { currencyCode, url, x.getMessage() }); } } } } } log.info("fetched exchange rates from {}, took {} ms", url, (System.currentTimeMillis() - start)); //Add Bitcoin information if (rates.size() == 0) { int i = 0; i++; } else { rates.put(CoinDefinition.cryptsyMarketCurrency, new ExchangeRate(CoinDefinition.cryptsyMarketCurrency, GenericUtils.toNanoCoins(String.format("%.8f", btcRate).replace(",", "."), 0), cryptsyValue ? "pubapi.cryptsy.com" : "data.bter.com")); rates.put("m" + CoinDefinition.cryptsyMarketCurrency, new ExchangeRate("m" + CoinDefinition.cryptsyMarketCurrency, GenericUtils.toNanoCoins( String.format("%.5f", btcRate * 1000).replace(",", "."), 0), cryptsyValue ? "pubapi.cryptsy.com" : "data.bter.com")); } return rates; } else { log.warn("http status {} when fetching {}", 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:com.bw.hawksword.wiktionary.SimpleWikiHelper.java
/** * Read and return the content for a specific Wiktionary page. This makes a * lightweight API call, and trims out just the page content returned. * Because this call blocks until results are available, it should not be * run from a UI thread./*from w w w . ja v a2s . c o m*/ * * @param title The exact title of the Wiktionary page requested. * @param expandTemplates If true, expand any wiki templates found. * @return Exact content of page. * @throws ApiException If any connection or server error occurs. * @throws ParseException If there are problems parsing the response. */ public static String getPageContent(String title, boolean expandTemplates) throws ApiException, ParseException { // Encode page title and expand templates if requested String encodedTitle = Uri.encode(title); String expandClause = expandTemplates ? WIKTIONARY_EXPAND_TEMPLATES : ""; // Query the API for content String content = getUrlContent(String.format(WIKTIONARY_PAGE, encodedTitle, expandClause)); try { // Drill into the JSON response to find the content body JSONObject response = new JSONObject(content); JSONObject query = response.getJSONObject("query"); JSONObject pages = query.getJSONObject("pages"); JSONObject page = pages.getJSONObject((String) pages.keys().next()); JSONArray revisions = page.getJSONArray("revisions"); JSONObject revision = revisions.getJSONObject(0); return revision.getString("*"); } catch (JSONException e) { throw new ParseException("Problem parsing API response", e); } }
From source file:org.official.json.CookieList.java
/** * Convert a JSONObject into a cookie list. A cookie list is a sequence * of name/value pairs. The names are separated from the values by '='. * The pairs are separated by ';'. The characters '%', '+', '=', and ';' * in the names and values are replaced by "%hh". * @param jo A JSONObject/*from w w w .j av a2s . co m*/ * @return A cookie list string * @throws JSONException */ public static String toString(JSONObject jo) throws JSONException { boolean b = false; Iterator<String> keys = jo.keys(); String string; StringBuilder sb = new StringBuilder(); while (keys.hasNext()) { string = keys.next(); if (!jo.isNull(string)) { if (b) { sb.append(';'); } sb.append(Cookie.escape(string)); sb.append("="); sb.append(Cookie.escape(jo.getString(string))); b = true; } } return sb.toString(); }
From source file:com.mi.xserv.XservBase.java
protected String urlEncodedJSON(JSONObject params) { String url_encode = ""; if (params != null) { Iterator<?> keys = params.keys(); while (keys.hasNext()) { String key = (String) keys.next(); String value = ""; try { value = params.get(key).toString(); } catch (JSONException ignored) { }/* w w w. j av a2 s . c om*/ try { if (url_encode.length() > 0) { url_encode += "&"; } url_encode += URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8"); } catch (UnsupportedEncodingException ignored) { } } } return url_encode; }
From source file:com.soomla.store.domain.data.VirtualGood.java
/** * Converts the current {@link VirtualGood} to a JSONObject. * @return a JSONObject representation of the current {@link VirtualGood}. *//* ww w .j a v a 2 s . co m*/ public JSONObject toJSONObject() { JSONObject parentJsonObject = super.toJSONObject(); JSONObject jsonObject = new JSONObject(); try { Iterator<?> keys = parentJsonObject.keys(); while (keys.hasNext()) { String key = (String) keys.next(); jsonObject.put(key, parentJsonObject.get(key)); } JSONObject priceModelObject = AbstractPriceModel.priceModelToJSONObject(mPriceModel); jsonObject.put(JSONConsts.GOOD_PRICE_MODEL, priceModelObject); } catch (JSONException e) { if (StoreConfig.debug) { Log.d(TAG, "An error occurred while generating JSON object."); } } return jsonObject; }
From source file:org.godotengine.godot.Utils.java
public static Map<String, Object> jsonToMap(String jsonData) { JSONObject jobject = null; try {//from ww w.j av a2 s . c om jobject = new JSONObject(jsonData); } catch (JSONException e) { Utils.d("JSONObject exception: " + e.toString()); } Map<String, Object> retMap = new HashMap<String, Object>(); Iterator<String> keysItr = jobject.keys(); while (keysItr.hasNext()) { try { String key = keysItr.next(); Object value = jobject.get(key); retMap.put(key, value); } catch (JSONException e) { Utils.d("JSONObject get key error" + e.toString()); } } return retMap; }
From source file:com.example.administrator.datarequest.ningworld.HttpHeaders.java
@Override public void setJSONString(String jsonString) throws JSONException { mSource.clear();//from w ww.j a v a2 s. c o m JSONObject jsonObject = new JSONObject(jsonString); Iterator<String> keySet = jsonObject.keys(); while (keySet.hasNext()) { String key = keySet.next(); String value = jsonObject.optString(key); JSONArray values = new JSONArray(value); if (values != null) for (int i = 0; i < values.length(); i++) add(key, values.optString(i)); } }
From source file:com.facebook.config.AbstractExpandedConfJSONProvider.java
private JSONObject getExpandedJSONConfig() throws JSONException { Set<String> traversedFiles = new HashSet<>(); Queue<String> toTraverse = new LinkedList<>(); // Seed the graph traversal with the root node traversedFiles.add(root);/*from ww w. ja v a 2s . c o m*/ toTraverse.add(root); // Policy: parent configs will override children (included) configs JSONObject expanded = new JSONObject(); while (!toTraverse.isEmpty()) { String current = toTraverse.remove(); JSONObject json = load(current); JSONObject conf = json.getJSONObject(CONF_KEY); Iterator<String> iter = conf.keys(); while (iter.hasNext()) { String key = iter.next(); // Current config will get to insert keys before its include files if (!expanded.has(key)) { expanded.put(key, conf.get(key)); } } // Check if the file itself has any included files if (json.has(INCLUDES_KEY)) { JSONArray includes = json.getJSONArray(INCLUDES_KEY); for (int idx = 0; idx < includes.length(); idx++) { String include = resolve(current, includes.getString(idx)); if (traversedFiles.contains(include)) { LOG.warn("Config file was included twice: " + include); } else { toTraverse.add(include); traversedFiles.add(include); } } } } return expanded; }
From source file:com.norman0406.slimgress.API.Knobs.RecycleKnobs.java
public RecycleKnobs(JSONObject json) throws JSONException { super(json);/*from w w w .j a v a 2s. c om*/ mRecycleValuesMap = new HashMap<String, List<Integer>>(); JSONObject recycleValuesMap = json.getJSONObject("recycleValuesMap"); Iterator<?> it = recycleValuesMap.keys(); while (it.hasNext()) { String key = (String) it.next(); mRecycleValuesMap.put(key, getIntArray(recycleValuesMap, key)); } }
From source file:com.example.android.notepad.CMNotesProvider.java
@Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { String[] keys = null;//from w ww .ja v a 2 s .c om switch (sUriMatcher.match(uri)) { case NOTES: //qb.setProjectionMap(sNotesProjectionMap); break; case NOTE_ID: //qb.setProjectionMap(sNotesProjectionMap); //qb.appendWhere(Notes._ID + "=" + uri.getPathSegments().get(1)); keys = new String[] { uri.getPathSegments().get(1) }; break; case LIVE_FOLDER_NOTES: //qb.setProjectionMap(sLiveFolderProjectionMap); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } // Get the database and run the query //SQLiteDatabase db = mOpenHelper.getReadableDatabase(); //Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy); CMAdapter cmadapter = new CMAdapter(); JSONObject objects = cmadapter.getValues(keys); MatrixCursor c = new MatrixCursor(projection); // objects is a map of key => value mappings, where key is the _id Iterator<String> note_ids = objects.keys(); while (note_ids.hasNext()) { String id = note_ids.next(); RowBuilder row = c.newRow(); for (String field : projection) { if (field.equals(Notes._ID)) { row.add(id); } else { String val = "bad entry"; try { val = objects.getJSONObject(id).getString(field); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } row.add(val); } } } // Tell the cursor what uri to watch, so it knows when its source data changes c.setNotificationUri(getContext().getContentResolver(), uri); return c; }