List of usage examples for org.json JSONObject keys
public Iterator keys()
From source file:at.alladin.rmbt.db.QoSTestObjective.java
@SuppressWarnings("unchecked") public String toHtml() { StringBuilder sb = new StringBuilder(); sb.append("<h3>QoS-Test (uid: " + getUid() + ", test_class: " + getTestClass() + ")</h3>"); if (getObjective() != null) { try {/*from ww w .j a va 2 s. co m*/ JSONObject objectives = new JSONObject(getObjective()); Iterator<String> keys = objectives.keys(); sb.append("<b>Test objectives (as plain text):</b> <ul>"); while (keys.hasNext()) { String key = keys.next(); sb.append("<li><i>" + key + "</i>: " + objectives.optString(key) + "</li>"); } sb.append("</ul>"); sb.append("<b>Test objectives (as hstore representation):</b> " + Helperfunctions.json2hstore(objectives, null) + "<br><br>"); if (testSummary != null) { sb.append("<b>Test summary (test_summary):</b> <a href=\"#" + testSummary.replaceAll("[\\-\\+\\.\\^:,]", "_") + "\">" + testSummary + "</a><br><br>"); } else { sb.append("<b>Test summary (test_summary):</b> <i>NULL</i><br><br>"); } if (testDescription != null) { sb.append("<b>Test description (test_desc):</b> <a href=\"#" + testDescription.replaceAll("[\\-\\+\\.\\^:,]", "_") + "\">" + testDescription + "</a><br><br>"); } else { sb.append("<b>Test description (test_desc):</b> <i>NULL</i><br><br>"); } } catch (JSONException e) { sb.append( "<b><i>incorrect test objectives format:</i></b><ul><li>" + getObjective() + "</li></ul>"); e.printStackTrace(); } } else { sb.append("<b><i>no objectives set for this test</i></b>"); } sb.append("<b>Expected test results (as hstore representation):</b><ul>"); if (getResults() != null) { JSONArray resultsJson; try { resultsJson = new JSONArray(getResults()); for (int i = 0; i < resultsJson.length(); i++) { try { final JSONObject expected = resultsJson.getJSONObject(i); sb.append("<li>" + Helperfunctions.json2htmlWithLinks(expected) + "</li>"); } catch (Exception e) { e.printStackTrace(); sb.append("<li>incorrect expected test result format</li>"); } } } catch (JSONException e1) { sb.append("<li>incorrect expected test result format</li>"); } } else { sb.append("<li><i>No expected results set for this test</i></li>"); } sb.append("</ul>"); return sb.toString(); }
From source file:com.fortydegree.ra.data.JsonUnmarshaller.java
public static Marker processGeoserviceJSONObject(JSONObject jo) throws JSONException { String type = jo.getString("type"); String metadata = jo.getString("metadata"); JSONObject jsonMetadata = new JSONObject(metadata); String title = jsonMetadata.optString("title"); Marker m = new Marker(jo.getDouble("latitude"), jo.getDouble("longitude"), jo.getDouble("altitude")); m.title = title;//from w ww . j a va 2s .c o m m.distance = jo.getDouble("distance"); @SuppressWarnings("rawtypes") Iterator metadataIter = jsonMetadata.keys(); while (metadataIter.hasNext()) { String key = metadataIter.next().toString(); m.setData(key, jsonMetadata.getString(key)); } m.setData("title", title); m.setData("type", type); return m; }
From source file:edu.mit.scratch.ScratchProject.java
public ScratchProject update() throws ScratchProjectException { try {/*w ww . j a v a 2 s .co m*/ final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build(); final CookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en"); lang.setDomain(".scratch.mit.edu"); lang.setPath("/"); cookieStore.addCookie(lang); final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig) .setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64)" + " AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/" + "537.36") .setDefaultCookieStore(cookieStore).build(); CloseableHttpResponse resp; final HttpUriRequest update = RequestBuilder.get() .setUri("https://scratch.mit.edu/api/v1/project/" + this.getProjectID() + "/?format=json") .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8") .addHeader("Referer", "https://scratch.mit.edu").addHeader("Origin", "https://scratch.mit.edu") .addHeader("Accept-Encoding", "gzip, deflate, sdch") .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json") .addHeader("X-Requested-With", "XMLHttpRequest").build(); try { resp = httpClient.execute(update); System.out.println(resp.getStatusLine().toString()); } catch (final IOException e) { e.printStackTrace(); throw new ScratchProjectException(); } BufferedReader rd; try { rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())); } catch (UnsupportedOperationException | IOException e) { e.printStackTrace(); throw new ScratchProjectException(); } final StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) result.append(line); System.out.println("projdata:" + result.toString()); final JSONObject jsonOBJ = new JSONObject(result.toString().trim()); final Iterator<?> keys = jsonOBJ.keys(); while (keys.hasNext()) { final String key = "" + keys.next(); final Object o = jsonOBJ.get(key); if (o instanceof JSONObject) this.creator = "" + ((JSONObject) o).get("username"); else { final String val = "" + o; switch (key) { case "creator": this.creator = val; break; case "datetime_shared": this.share_date = val; break; case "description": this.description = val; break; case "favorite_count": this.favorite_count = val; break; case "id": this.ID = Integer.parseInt(val); break; case "love_count": this.love_count = val; break; case "resource_uri": this.resource_uri = val; break; case "thumbnail": this.thumbnail = val; break; case "title": this.title = val; break; case "view_count": this.view_count = val; break; default: System.out.println("Missing reference:" + key); break; } } } } catch (final UnsupportedEncodingException e) { e.printStackTrace(); throw new ScratchProjectException(); } catch (final IOException e) { e.printStackTrace(); throw new ScratchProjectException(); } return this; }
From source file:org.indigo.cdmi.backend.radosgw.JsonResponseTranlator.java
/** * Basing on passed profileInfo, creates object of type BackendCapability. * //www . ja v a 2s . c om * @param profileInfo Profile described in JSOSObject. * @return Object of BackendCapability derived from passed profileInfo. */ private BackendCapability createBackedCapability(JSONObject profileInfo) { /* * determine value of name parameter to be used with BackendCapability */ String profileName = profileInfo.getString(JSON_KEY_NAME); /* * determine value of type attribute to be used with BackendCapability */ BackendCapability.CapabilityType type = null; String typeAsString = profileInfo.getString(JSON_KEY_TYPE); switch (typeAsString) { case CDMI_OBJECT_TYPE_CONTAINER: type = BackendCapability.CapabilityType.CONTAINER; break; case CDMI_OBJECT_TYPE_DATAOBJECT: type = BackendCapability.CapabilityType.DATAOBJECT; break; default: throw new RuntimeException("Unknown capability type"); } /* * create new instance of BackendCapability * (it is empty for now, the metadata and capabilities properties have to be created, * populated and passed to the BackendCapability object) */ final BackendCapability returnBackendCapability = new BackendCapability(profileName, type); /* * create capabilities object (to be populated and injected into returned BackendCapability) */ Map<String, Object> capabilities = new HashMap<>(); /* * Add always present capabilities */ capabilities.put("cdmi_capabilities_templates", "true"); capabilities.put("cdmi_capabilities_exact_inherit", "true"); /* * create metadata object (to be populated and injected into returned BackendCapability) */ Map<String, Object> metadata = new HashMap<>(); /* * iterate through metadata in profileInfo and populate capabilities and * metadata in BackendCapability object */ JSONObject metadataObj = profileInfo.getJSONObject(JSON_KEY_METADATA); log.debug("Processing metadata array from profile returned by BackendGateway"); Iterator<?> keys = metadataObj.keys(); while (keys.hasNext()) { /* * get key name for current item in metadata array */ String key = (String) keys.next(); /* * get value assigned to the current key, and convert the value to String * NOTE: The convention is required because returned value can be for example of array type * or of another JSONObject, it not necessary has to be String, so usage of * metadataObj.getString(key) would be wrong */ Object valueObj = metadataObj.get(key); log.debug("Current metadata key: {}", key); log.debug("Current metadata value: {}", valueObj); log.debug("Metadata value class/type is: {}", valueObj.getClass()); /* * Create key and value to be added to capabilities. * Separate variables for key and value objects are introduced deliberately * to note that in future or in case of any special values, an additional * logic / calculation can be required to obtain key and value to be used * with capabilities map */ String cdmiCapabilityKey = key; String cdmiCapabilityValue = "true"; /* * add "calculated" key and value to the capabilities map */ capabilities.put(cdmiCapabilityKey, cdmiCapabilityValue); /* * see above comments for capabilities related keys and values */ String cdmiMetadataKey = key; Object cdmiMetadataValue = valueObj; /* * add "calculated" key and value to the metadata map */ metadata.put(cdmiMetadataKey, cdmiMetadataValue); } // while() //capabilities.put("cdmi_capabilities_allowed", "true"); /* * process allowed profiles */ try { JSONArray allowedProfiles = profileInfo.getJSONArray(JSON_KEY_ALLOWED_PROFILES); String profilesUris = profilesToUris(allowedProfiles, retriveObjectTypeAsString(profileInfo)); log.debug("allowedProfiles: {}", allowedProfiles); log.debug("profilesURIs: {}", profilesUris); metadata.put("cdmi_capabilities_allowed", profilesUris); } catch (JSONException ex) { log.debug("No {} key in processed JSON document", JSON_KEY_ALLOWED_PROFILES); } // try{} returnBackendCapability.setCapabilities(capabilities); returnBackendCapability.setMetadata(metadata); return returnBackendCapability; }
From source file:org.indigo.cdmi.backend.radosgw.JsonResponseTranlator.java
/** * Basing on passed JSON in String format, creates object of CdmiObjecStatus. * (Translates JSON in String format into CdmiObjectStatus) *///from w ww . ja va 2 s . c o m @Override public CdmiObjectStatus getCdmiObjectStatus(String gatewayResponse) { //log.debug("Translate {} to CdmiObjectStatus", gatewayResponse); Map<String, Object> monitoredAttributes = new HashMap<>(); JSONObject profile = new JSONObject(gatewayResponse); //log.debug("profile: {}", profile); JSONObject metadataProvided = profile.getJSONObject("metadata_provided"); //log.debug("metadata_provided: {}", metadataProvided); Iterator<?> keys = metadataProvided.keys(); while (keys.hasNext()) { /* * get key name for current item in metadata array */ String key = (String) keys.next(); //log.debug("key: {}", key); Object metadataProvidedAsObj = metadataProvided.get(key); //String metadataProvidedAsString = metadataProvidedAsObj.toString(); //monitoredAttributes.put(key, metadataProvidedAsString); monitoredAttributes.put(key, metadataProvidedAsObj); } String profileName = profile.getString("name"); String type = profile.getString("type"); String currentCapabilitiesUri = "/cdmi_capabilities/" + type + "/" + profileName; return new CdmiObjectStatus(monitoredAttributes, currentCapabilitiesUri, null); }
From source file:org.cloudfoundry.client.lib.util.JsonUtil.java
public static List<String> keys(JSONObject j) { List<String> list = new ArrayList<String>(); @SuppressWarnings("unchecked") Iterator<Object> i = j.keys(); while (i.hasNext()) { list.add(i.next().toString());/* w w w. j av a 2s . c o m*/ } return list; }
From source file:fi.kinetik.android.currencies.spi.openexchange.OpenExchangeRatesSpi.java
private void parseRates(ArrayList<ContentProviderOperation> operations, JSONObject jsonObj) throws JSONException { final long updated = jsonObj.getLong(Keys.TIMESTAMP); final String base = jsonObj.getString(Keys.BASE); final JSONObject rates = jsonObj.getJSONObject(Keys.RATES); final Iterator iter = rates.keys(); while (iter.hasNext()) { final String currency = (String) iter.next(); final double rate = rates.getDouble(currency); operations.add(ConversionRate.newUpdateOperation(currency, OpenExchangeRatesSpiFactory.PROVIDER_NAME, updated, rate));// w w w . ja va2 s. c om } }
From source file:com.orange.mmp.api.ws.jsonrpc.SimpleMapSerializer.java
@SuppressWarnings("unchecked") @Override// w ww .ja va2 s .c o m public Object unmarshall(SerializerState state, Class clazz, Object o) throws UnmarshallException { Map map = null; try { try { try { if (clazz.isInterface()) { map = new java.util.HashMap(); } else map = (Map) clazz.newInstance(); } catch (ClassCastException cce) { throw new UnmarshallException("invalid unmarshalling Class " + cce.getMessage()); } } catch (IllegalAccessException iae) { throw new UnmarshallException("no access unmarshalling object " + iae.getMessage()); } } catch (InstantiationException ie) { throw new UnmarshallException("unable to instantiate unmarshalling object " + ie.getMessage()); } JSONObject jso = (JSONObject) o; Iterator keys = jso.keys(); state.setSerialized(o, map); try { while (keys.hasNext()) { String key = (String) keys.next(); map.put(key, ser.unmarshall(state, null, jso.get(key))); } } catch (JSONException je) { throw new UnmarshallException("Could not read map: " + je.getMessage()); } return map; }
From source file:cz.muni.fi.japanesedictionary.entity.JapaneseCharacter.java
/** * Takes json string and parses it to map of dictionary references. * /*from w w w .j a v a 2 s . c o m*/ * @param jsonString - JSON string to be parsed */ public void parseDicRef(String jsonString) { if (jsonString == null || jsonString.length() < 1) { return; } Map<String, String> dicRefTemp = new HashMap<>(); JSONObject dicRefJson; try { dicRefJson = new JSONObject(jsonString); } catch (JSONException e) { Log.w(LOG_TAG, "getting parseJapaneseKeb() initial expression failed: " + e.toString()); return; } Iterator<?> keys = dicRefJson.keys(); while (keys.hasNext()) { String key = (String) keys.next(); String value; try { value = dicRefJson.getString(key); if (key != null && value != null) { dicRefTemp.put(key, value); } } catch (JSONException e) { Log.w(LOG_TAG, "parsing dicRef failed"); } } if (dicRefTemp.size() > 0) { for (String key : dicRefTemp.keySet()) { addDicRef(key, dicRefTemp.get(key)); } } }
From source file:com.extremeboredom.wordattack.utils.JSONUtils.java
/** * parse key-value pairs to map. ignore empty key, if getValue exception, put empty value * * @param sourceObj key-value pairs json * @return <ul>/*from w ww . j a v a2 s .c om*/ * <li>if sourceObj is null, return null</li> * <li>else parse entry one by one</li> * </ul> */ @SuppressWarnings("rawtypes") //No i18n public static Map<String, String> parseKeyAndValueToMap(JSONObject sourceObj) { if (sourceObj == null) { return null; } Map<String, String> keyAndValueMap = new HashMap<String, String>(); for (Iterator iter = sourceObj.keys(); iter.hasNext();) { String key = (String) iter.next(); keyAndValueMap.put(key, getString(sourceObj, key, "")); } return keyAndValueMap; }