List of usage examples for org.json JSONObject keys
public Iterator keys()
From source file:kevin.gvmsgarch.Worker.java
private HashSet<String> getFilterIds(String json, ContactFilter filter) { try {/*from w w w . j av a2s . co m*/ JSONObject messages = new JSONObject(json).getJSONObject("messages"); HashSet<String> keysToRemove = new HashSet<String>(); Iterator i = messages.keys(); while (i.hasNext()) { String key = (String) i.next(); if (!filter.process(messages.getJSONObject(key))) { keysToRemove.add(key); } } return keysToRemove; } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:kevin.gvmsgarch.Worker.java
private static Set<String> getMessageIds(String textContent) throws JSONException { HashSet<String> retval = new HashSet<String>(); JSONObject top = new JSONObject(textContent); JSONObject messages = top.getJSONObject("messages"); Iterator i = messages.keys(); if (!i.hasNext()) { retval = null;/*www . ja va2 s . c o m*/ } else { while (i.hasNext()) { retval.add(i.next().toString()); } } return retval; }
From source file:com.dopecoin.wallet.ExchangeRatesProvider.java
private static Map<String, ExchangeRate> requestExchangeRates(final URL url, float leafBtcConversion, final String userAgent, final String... fields) { final long start = System.currentTimeMillis(); HttpURLConnection connection = null; Reader reader = null;//ww w. jav a 2 s . c o m try { connection = (HttpURLConnection) url.openConnection(); 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) { final String rate = o.optString(field, null); if (rate != null) { try { BigDecimal btcRate = new BigDecimal(GenericUtils.toNanoCoins(rate, 0)); BigInteger leafRate = btcRate.multiply(BigDecimal.valueOf(leafBtcConversion)) .toBigInteger(); if (leafRate.signum() > 0) { rates.put(currencyCode, new ExchangeRate(currencyCode, leafRate, 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)); 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.citrus.mobile.OauthToken.java
public boolean createToken(JSONObject usertoken) { jsontoken = new JSONObject(); long expiry = new Date().getTime() / 1000l; try {// w w w. j ava 2 s. c o m expiry += usertoken.getLong("expires_in"); jsontoken.put("expiry", expiry); } catch (JSONException e) { e.printStackTrace(); } for (Iterator<?> keys = usertoken.keys(); keys.hasNext();) { String key = (String) keys.next(); try { jsontoken.put(key, usertoken.get(key)); } catch (JSONException e) { e.printStackTrace(); } } return storeToken(); }
From source file:net.freifunk.android.discover.model.NodesResponse.java
@Override public void onResponse(JSONObject jsonObject) { try {/*from w w w . ja v a 2s. com*/ JSONArray node_list = jsonObject.getJSONArray("nodes"); for (int i = 0; i < node_list.length(); i++) { JSONObject node = node_list.getJSONObject(i); List<String> mac_list = new ArrayList<String>(1); // MAC if (node.has("macs")) { String[] macs = ((String) node.get("macs")).split(","); mac_list = new ArrayList<String>(macs.length); for (String mac : macs) { mac_list.add(mac.trim()); } } else { mac_list.add(" "); } // Name String name = ((String) node.get("name")).trim(); // Firmware String firmware = String.valueOf(node.get("firmware")).trim(); // Flags Map<String, String> flags = new HashMap<String, String>(); JSONObject jflags = node.getJSONObject("flags"); Iterator flag = jflags.keys(); while (flag.hasNext()) { String key = (String) flag.next(); String val = String.valueOf(jflags.get(key)); flags.put(key, val); } // Geo LatLng pos = null; // Log.d(TAG, String.valueOf(node.get("geo"))); if (!String.valueOf(node.get("geo")).equals("null")) { JSONArray geo = node.getJSONArray("geo"); Double lat = (Double) geo.get(0); Double lng = (Double) geo.get(1); pos = new LatLng(lat, lng); } // Id String id = ((String) node.get("id")).trim(); Node n = new Node(mac_list, this.mCallingMap.getMapName(), name, firmware, flags, pos, id); Node.nodes.add(n); mCallback.onNodeAvailable(n); } } catch (JSONException e) { Log.e(TAG, "Seems something went wrong while loading Nodes for " + this.mCallingMap.getMapName() + ":" + e.toString()); } finally { mCallback.onResponseFinished(this.mCallingMap); } }
From source file:com.android.talkback.eventprocessor.ProcessorPhoneticLetters.java
/** * Get the mapping from letter to phonetic letter for a given locale. * The map is loaded as needed.//from w w w . jav a 2 s .c om */ private Map<String, String> getPhoneticLetterMap(String locale) { Map<String, String> map = mPhoneticLetters.get(locale); if (map == null) { // If there is no entry for the local, the map will be left // empty. This prevents future load attempts for that locale. map = new HashMap<String, String>(); mPhoneticLetters.put(locale, map); InputStream stream = mService.getResources().openRawResource(R.raw.phonetic_letters); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); StringBuilder stringBuilder = new StringBuilder(); String input; while ((input = reader.readLine()) != null) { stringBuilder.append(input); } stream.close(); JSONObject locales = new JSONObject(stringBuilder.toString()); JSONObject phoneticLetters = locales.getJSONObject(locale); if (phoneticLetters != null) { Iterator<?> keys = phoneticLetters.keys(); while (keys.hasNext()) { String letter = (String) keys.next(); map.put(letter, phoneticLetters.getString(letter)); } } } catch (java.io.IOException e) { LogUtils.log(this, Log.ERROR, e.toString()); } catch (JSONException e) { LogUtils.log(this, Log.ERROR, e.toString()); } } return map; }
From source file:io.teak.sdk.Helpers.java
private static Map<String, Object> toMap(JSONObject object) throws JSONException { Map<String, Object> map = new HashMap<>(); Iterator keysItr = object.keys(); while (keysItr.hasNext()) { String key = keysItr.next().toString(); Object value = object.get(key); if (value instanceof JSONArray) { value = toList((JSONArray) value); } else if (value instanceof JSONObject) { value = toMap((JSONObject) value); }//from ww w .ja v a2 s .c o m map.put(key, value); } return map; }
From source file:edu.cens.loci.classes.LociWifiFingerprint.java
@SuppressWarnings("unchecked") public LociWifiFingerprint(String json) throws JSONException { JSONObject jObj = new JSONObject(json); this.mEnter = jObj.getLong("enter"); this.mExit = jObj.getLong("exit"); this.mScanCount = jObj.getInt("count"); JSONObject jObjAPs = jObj.getJSONObject("aps"); Iterator<String> keys = jObjAPs.keys(); mAPs = new HashMap<String, APInfoMapItem>(); while (keys.hasNext()) { String bssid = keys.next(); mAPs.put(bssid, new APInfoMapItem(jObjAPs.getJSONObject(bssid))); }/*from w ww . j a va2 s .c o m*/ //Log.d(TAG, "constructing from json : " + this.toString()); }
From source file:wseproject.WikiJsonReader.java
public static String getWikiText(String article) { //System.out.println("Read and loaded JSON for: " + article); article = article.replace(" ", "_"); String srcURL = "http://en.wikipedia.org/w/api.php?action=query&prop=revisions&" + "rvprop=content&format=json&titles=" + article; try {// w ww . j av a2 s . c om JSONObject json = readJsonFromUrl(srcURL); JSONObject pages = json.getJSONObject("query").getJSONObject("pages"); //JSONObject pages = json.get Iterator i = pages.keys(); while (i.hasNext()) { String key = (String) i.next(); System.out.println(key); JSONObject page = pages.getJSONObject(key); JSONObject rev0 = page.getJSONArray("revisions").getJSONObject(0); String text = rev0.getString("*"); //System.out.println("Read and loaded JSON for: " + article); String t = text.toString(); //System.out.println(t); return t; } } catch (Exception e) { System.out.println("Failed to load JSON for: " + article); } return null; }
From source file:com.jsonstore.jackson.JsonOrgJSONObjectSerializer.java
protected void serializeContents(JSONObject value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException { Iterator<?> i = value.keys(); while (i.hasNext()) { String key = (String) i.next(); Class<?> cls;//from w ww . ja v a2 s . co m Object obj; try { obj = value.get(key); } catch (JSONException e) { throw new JsonGenerationException(e); } if ((obj == null) || (obj == JSONObject.NULL)) { jgen.writeNullField(key); continue; } jgen.writeFieldName(key); cls = obj.getClass(); if ((cls == JSONObject.class) || JSONObject.class.isAssignableFrom(cls)) { serialize((JSONObject) obj, jgen, provider); } else if ((cls == JSONArray.class) || JSONArray.class.isAssignableFrom(cls)) { JsonOrgJSONArraySerializer.instance.serialize((JSONArray) obj, jgen, provider); } else if (cls == String.class) { jgen.writeString((String) obj); } else if (cls == Integer.class) { jgen.writeNumber(((Integer) obj).intValue()); } else if (cls == Long.class) { jgen.writeNumber(((Long) obj).longValue()); } else if (cls == Boolean.class) { jgen.writeBoolean(((Boolean) obj).booleanValue()); } else if (cls == Double.class) { jgen.writeNumber(((Double) obj).doubleValue()); } else { provider.defaultSerializeValue(obj, jgen); } } }