List of usage examples for org.json JSONObject keys
public Iterator keys()
From source file:com.soomla.store.domain.data.StaticPriceModel.java
/** * Creates a {@link StaticPriceModel} with the given JSONObject. * @param jsonObject is a JSONObject representation of the required {@link StaticPriceModel}. * @return an instance of {@link StaticPriceModel}. * @throws JSONException/*from ww w . j a v a 2 s. c o m*/ */ public static StaticPriceModel fromJSONObject(JSONObject jsonObject) throws JSONException { JSONObject valuesJSONObject = jsonObject.getJSONObject(JSONConsts.GOOD_PRICE_MODEL_VALUES); Iterator<?> keys = valuesJSONObject.keys(); HashMap<String, Integer> values = new HashMap<String, Integer>(); while (keys.hasNext()) { String key = (String) keys.next(); values.put(key, valuesJSONObject.getInt(key)); } return new StaticPriceModel(values); }
From source file:de.jaetzold.philips.hue.HueBridge.java
private void parseLights(JSONObject lightsJson) { final Iterator<?> keys = lightsJson.keys(); while (keys.hasNext()) { Object key = keys.next(); try {/*from ww w . ja va2 s . c o m*/ Integer id = Integer.parseInt((String) key); HueLightBulb light = lights.get(id); if (light == null) { light = new HueLightBulb(this, id); lights.put(id, light); } final JSONObject lightJson = lightsJson.getJSONObject((String) key); light.parseLight(lightJson); } catch (Exception e) { if (e instanceof HueCommException) { throw e; } else { throw new HueCommException("Lights result parsing failed. Probably some unexpected format?", e); } } } }
From source file:de.jaetzold.philips.hue.HueBridge.java
private void parseGroups(JSONObject groupsJson) { final Iterator<?> keys = groupsJson.keys(); while (keys.hasNext()) { Object key = keys.next(); try {//from ww w.ja v a 2s.c om Integer id = Integer.parseInt((String) key); HueLightGroup group = groups.get(id); if (group == null) { group = new HueLightGroup(this, id); groups.put(id, group); } final JSONObject lightJson = groupsJson.getJSONObject((String) key); group.name = lightJson.getString("name"); final JSONArray lightsArray = lightJson.getJSONArray("lights"); for (int i = 0; i < lightsArray.length(); i++) { Integer lightId = Integer.parseInt(lightsArray.getString(i)); final HueLightBulb light = getLight(lightId); if (light == null) { //noinspection ThrowCaughtLocally throw new HueCommException("Can not find light with id " + lightId); } else { group.lights.put(lightId, light); } } } catch (Exception e) { if (e instanceof HueCommException) { throw e; } else { throw new HueCommException("Groups result parsing failed. Probably some unexpected format?", e); } } } }
From source file:com.nosoop.json.VDF.java
/** * Recursively searches for JSONObjects, checking if they should be * formatted as arrays, then converted./*from w w w .ja va 2 s.c om*/ * * @param object An input JSONObject converted from VDF. * @return JSONObject containing the input JSONObject with objects changed * to arrays where applicable. * @throws JSONException */ private static JSONObject convertVDFArrays(JSONObject object) throws JSONException { JSONObject resp = new JSONObject(); if (!object.keys().hasNext()) { return resp; } for (@SuppressWarnings("unchecked") Iterator<String> iter = object.keys(); iter.hasNext();) { String name = iter.next(); JSONObject thing = object.optJSONObject(name); if (thing != null) { // Note: Empty JSONObjects are also treated as arrays. if (containsVDFArray(thing)) { @SuppressWarnings("unchecked") Iterator<String> iter2 = thing.keys(); List<String> sortingKeys = new ArrayList<String>(); while (iter2.hasNext()) sortingKeys.add(iter2.next()); Collections.sort(sortingKeys, new Comparator<String>() { // Integers-as-strings comparator. @Override public int compare(String t, String t1) { int i = Integer.parseInt(t), i1 = Integer.parseInt(t1); return i - i1; } }); JSONArray sortedKeys = new JSONArray(sortingKeys); if (sortedKeys.length() > 0) { JSONArray sortedObjects = thing.toJSONArray(sortedKeys); for (int i = 0; i < sortedObjects.length(); i++) { JSONObject arrayObject = sortedObjects.getJSONObject(i); /** * See if any values are also JSONObjects that * should be arrays. */ sortedObjects.put(i, convertVDFArrays(arrayObject)); } /** * If this JSONObject represents a non-empty array in * VDF format, convert it to a JSONArray. */ resp.put(name, sortedObjects); } else { /** * If this JSONObject represents an empty array, give it * an empty JSONArray. */ resp.put(name, new JSONArray()); } } else { /** * If this JSONObject is not a VDF array, see if its values * are before adding. */ resp.put(name, convertVDFArrays(thing)); } } else { /** * It's a plain data value. Add it in. */ resp.put(name, object.get(name)); } } /** * Return the converted JSONObject. */ return resp; }
From source file:com.nosoop.json.VDF.java
/** * Checks that a JSONObject converted from a VDF file is an array. If so, * the only keys in the JSONObject are a continues set of integers * represented by Strings starting from "0". Note that empty JSONObjects are * also treated as arrays./* w w w . j a va 2s . c om*/ * * @param object The JSONObject to check for a VDF-formatted array. * @return Whether or not the JSONObject is a VDF-formatted array. */ private static boolean containsVDFArray(JSONObject object) { int indices = object.length(); int[] index = new int[indices]; for (int i = 0; i < indices; i++) { index[i] = -1; } /** * Fail if we encounter a non-integer, if a value isn't a JSONObject, * or if the key is a number that is larger than the size of the array * (meaning we're missing a value). */ for (@SuppressWarnings("unchecked") Iterator<String> iter = object.keys(); iter.hasNext();) { String name = iter.next(); if (object.optJSONObject(name) == null) { return false; } try { int i = Integer.parseInt(name); if (i >= indices) { return false; } index[i] = i; } catch (NumberFormatException e) { return false; } } // Fail if we are missing any values (e.g., 0, 1, 2, 3, 4, 5, 7, 8, 9). for (int i = 0; i < indices; i++) { if (index[i] != i) { return false; } } return true; }
From source file:gr.cti.android.experimentation.controller.api.HistoryController.java
@ApiOperation(value = "experiment") @ResponseBody//w w w.ja va 2 s .c o m @RequestMapping(value = { "/entities/{entity_id}/readings" }, method = RequestMethod.GET) public HistoricDataDTO experimentView(@PathVariable("entity_id") final String entityId, @RequestParam(value = "attribute_id") final String attributeId, @RequestParam(value = "from") final String from, @RequestParam(value = "to") final String to, @RequestParam(value = "all_intervals", required = false, defaultValue = "true") final boolean allIntervals, @RequestParam(value = "rollup", required = false, defaultValue = "") final String rollup, @RequestParam(value = "function", required = false, defaultValue = "avg") final String function) { final HistoricDataDTO historicDataDTO = new HistoricDataDTO(); historicDataDTO.setEntity_id(entityId); historicDataDTO.setAttribute_id(attributeId); historicDataDTO.setFunction(function); historicDataDTO.setRollup(rollup); historicDataDTO.setFrom(from); historicDataDTO.setTo(to); historicDataDTO.setReadings(new ArrayList<>()); final List<TempReading> tempReadings = new ArrayList<>(); long fromLong = parseDateMillis(from); long toLong = parseDateMillis(to); final String[] parts = entityId.split(":"); final String phoneId = parts[parts.length - 1]; LOGGER.info("phoneId: " + phoneId + " from: " + from + " to: " + to); final Set<Result> results = resultRepository.findByDeviceIdAndTimestampBetween(Integer.parseInt(phoneId), fromLong, toLong); final Set<Result> resultsCleanup = new HashSet<>(); for (final Result result : results) { try { final JSONObject readingList = new JSONObject(result.getMessage()); final Iterator keys = readingList.keys(); while (keys.hasNext()) { final String key = (String) keys.next(); if (key.contains(attributeId)) { tempReadings.add(new TempReading(result.getTimestamp(), readingList.getDouble(key))); } } } catch (JSONException e) { resultsCleanup.add(result); } catch (Exception e) { LOGGER.error(e, e); } } resultRepository.delete(resultsCleanup); List<TempReading> rolledUpTempReadings = new ArrayList<>(); if ("".equals(rollup)) { rolledUpTempReadings = tempReadings; } else { final Map<Long, SummaryStatistics> dataMap = new HashMap<>(); for (final TempReading tempReading : tempReadings) { Long millis = null; //TODO: make rollup understand the first integer part if (rollup.endsWith("m")) { millis = new DateTime(tempReading.getTimestamp()).withMillisOfSecond(0).withSecondOfMinute(0) .getMillis(); } else if (rollup.endsWith("h")) { millis = new DateTime(tempReading.getTimestamp()).withMillisOfSecond(0).withSecondOfMinute(0) .withMinuteOfHour(0).getMillis(); } else if (rollup.endsWith("d")) { millis = new DateTime(tempReading.getTimestamp()).withMillisOfDay(0).getMillis(); } if (millis != null) { if (!dataMap.containsKey(millis)) { dataMap.put(millis, new SummaryStatistics()); } dataMap.get(millis).addValue(tempReading.getValue()); } } final TreeSet<Long> treeSet = new TreeSet<>(); treeSet.addAll(dataMap.keySet()); if (allIntervals) { fillMissingIntervals(treeSet, rollup, toLong); } for (final Long millis : treeSet) { if (dataMap.containsKey(millis)) { rolledUpTempReadings.add(parse(millis, function, dataMap.get(millis))); } else { rolledUpTempReadings.add(new TempReading(millis, 0)); } } } for (final TempReading tempReading : rolledUpTempReadings) { List<Object> list = new ArrayList<>(); list.add(df.format(tempReading.getTimestamp())); list.add(tempReading.getValue()); historicDataDTO.getReadings().add(list); } return historicDataDTO; }
From source file:pt.webdetails.cpf.persistence.PersistenceEngine.java
public ODocument createDocument(String baseClass, JSONObject json) { ODocument doc = new ODocument(baseClass); @SuppressWarnings("unchecked") Iterator<String> fields = json.keys(); while (fields.hasNext()) { String field = fields.next(); if (field.equals("key")) { continue; }/*from www .j ava 2 s . co m*/ try { Object value = json.get(field); if (value instanceof JSONObject) { doc.field(field, createDocument(baseClass + "_" + field, (JSONObject) value)); JSONObject obj = json.getJSONObject(field); logger.debug("obj:" + obj.toString(JSON_INDENT)); } else { doc.field(field, value); } } catch (JSONException e) { logger.error(e); } } return doc; }
From source file:org.jandroid2cloud.connection.ChannelHandler.java
@Override public void message(String rawMsg) { logger.debug("Received message from server:" + rawMsg); try {//from ww w . j av a 2 s . com JSONObject jsonMessage = new JSONObject(new JSONTokener(rawMsg)); JSONObject links = (JSONObject) jsonMessage.opt("links"); if (links == null) { JSONObject link = jsonMessage.optJSONObject("link"); handleLink(link); } else { Iterator it = links.keys(); while (it.hasNext()) { String s = (String) it.next(); if (s != null && !s.isEmpty()) { JSONObject o = links.getJSONObject(s); handleLink(o); } } } Map<String, String> params = new HashMap<String, String>(); params.put("links", rawMsg); String response = oauth.makeRequest("http://" + config.getHost() + "/markread", Verb.POST, params); logger.debug("Marked message as read"); } catch (JSONException e) { e.printStackTrace(); } catch (NetworkException e) { logger.error(NotificationAppender.MARKER, "Could not mark links as read.\n" + "You will not receive more links until that is done.\n" + "See log for details", e); } }
From source file:com.clearcenter.mobile_demo.mdStatusActivity.java
public List<JSONObject> sortedSamplesList(String data) { SortedMap<String, JSONObject> map = new TreeMap<String, JSONObject>(); try {/*from w ww . j a v a2s . c o m*/ int version = 0; JSONObject json_data = new JSONObject(data); if (json_data.has("version")) version = json_data.getInt("version"); if (version < 1 && json_data.has("time")) { String key = json_data.getString("time"); map.put(key, json_data); } else if (version >= 1 && json_data.has("samples") && !json_data.isNull("samples")) { json_data = json_data.getJSONObject("samples"); Iterator i = json_data.keys(); while (i.hasNext()) { String key = i.next().toString(); JSONObject sample = json_data.getJSONObject(key); sample.put("time", key); map.put(key, sample); } } } catch (JSONException e) { Log.e(TAG, "JSONException", e); } return new LinkedList<JSONObject>(map.values()); }
From source file:org.sleeksnap.ScreenSnapper.java
/** * Load settings/*from w w w . ja v a 2 s . co m*/ */ private void loadSettings(final boolean resetConfig) throws Exception { final File configFile = new File(Util.getWorkingDirectory(), Application.NAME.toLowerCase() + ".conf"); if (!configFile.exists() || resetConfig) { configuration.setFile(configFile); loadDefaultConfiguration(); } else { configuration.load(configFile); } if (configuration.contains("uploaders")) { final JSONObject uploadConfig = configuration.getJSONObject("uploaders"); if (convertUploadDefinition(uploadConfig, BufferedImage.class, ImageUpload.class) || convertUploadDefinition(uploadConfig, String.class, TextUpload.class) || convertUploadDefinition(uploadConfig, File.class, FileUpload.class) || convertUploadDefinition(uploadConfig, URL.class, URLUpload.class)) { logger.info("Converted upload definitions from old configuration."); configuration.save(); } @SuppressWarnings("unchecked") final Iterator<Object> it$ = uploadConfig.keys(); while (it$.hasNext()) { final String key = it$.next().toString(); final String className = uploadConfig.getString(key); @SuppressWarnings("unchecked") final Class<? extends Upload> clType = (Class<? extends Upload>) Class.forName(key); if (clType != null) { setDefaultUploader(clType, className); } } } if (configuration.contains("startOnStartup") && configuration.getBoolean("startOnStartup")) { // Verify that the paths match, useful for upgrading since it won't // open the old file. final File current = FileUtils.getJarFile(ScreenSnapper.class); if (!current.isDirectory()) { Updater.verifyAutostart(current, VerificationMode.INSERT); } } }