Example usage for org.json JSONObject keys

List of usage examples for org.json JSONObject keys

Introduction

In this page you can find the example usage for org.json JSONObject keys.

Prototype

public Iterator keys() 

Source Link

Document

Get an enumeration of the keys of the JSONObject.

Usage

From source file:com.hueemulator.lighting.utils.TestUtils.java

@SuppressWarnings("unchecked")
private static Object convertJsonElement(Object elem) throws JSONException {
    if (elem instanceof JSONObject) {
        JSONObject obj = (JSONObject) elem;
        Iterator<String> keys = obj.keys();
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        while (keys.hasNext()) {
            String key = keys.next();
            jsonMap.put(key, convertJsonElement(obj.get(key)));
        }/*w w w.  jav  a 2  s  . c om*/
        return jsonMap;
    } else if (elem instanceof JSONArray) {
        JSONArray arr = (JSONArray) elem;
        Set<Object> jsonSet = new HashSet<Object>();
        for (int i = 0; i < arr.length(); i++) {
            jsonSet.add(convertJsonElement(arr.get(i)));
        }
        return jsonSet;
    } else {
        return elem;
    }
}

From source file:nl.b3p.viewer.stripes.IbisMergeFeaturesActionBean.java

/**
 * Force the workflow status attribute on the feature. This will handle the
 * case where the {@code extraData} attribute is a piecs of json with the
 * workflow, eg//www .  j av a2  s  .  c  o m
 * {@code {workflow_status:'afgevoerd',datum_mutatie:'2015-12-01Z00:00'}}.
 *
 * @param features A list of features to be modified
 * @return the list of modified features that are about to be committed to
 * the datastore
 *
 * @throws JSONException if json parsing failed
 */
@Override
protected List<SimpleFeature> handleExtraData(List<SimpleFeature> features) throws JSONException {
    JSONObject json = new JSONObject(this.getExtraData());
    Iterator items = json.keys();
    while (items.hasNext()) {
        String key = (String) items.next();
        for (SimpleFeature f : features) {
            log.debug(String.format("Setting value: %s for attribute: %s on feature %s", json.get(key), key,
                    f.getID()));
            f.setAttribute(key, json.get(key));
            if (key.equalsIgnoreCase(WORKFLOW_FIELDNAME)) {
                newWorkflowStatus = WorkflowStatus.valueOf(json.getString(key));
            }
        }
    }
    return features;
}

From source file:com.joyfulmongo.db.JFCommand.java

protected List<ContainerObject> findChildObject(JSONObject parentObj) {
    List<ContainerObject> childs = new ArrayList<ContainerObject>(0);
    Iterator<String> keys = parentObj.keys();
    while (keys.hasNext()) {
        String key = keys.next();
        Object obj = parentObj.get(key);
        if (obj instanceof JSONObject) {
            ContainerObject typedObj = ContainerObjectFactory.getChildObject(key, (JSONObject) obj);
            if (typedObj != null) {
                childs.add(typedObj);//www .jav  a 2s .  c o  m
            }
        }
    }

    return childs;
}

From source file:de.schildbach.wallet.data.ExchangeRatesProvider.java

private Map<String, ExchangeRate> requestExchangeRates() {
    final Stopwatch watch = Stopwatch.createStarted();

    final Request.Builder request = new Request.Builder();
    request.url(BITCOINAVERAGE_URL);
    request.header("User-Agent", userAgent);

    final Call call = Constants.HTTP_CLIENT.newCall(request.build());
    try {//from   w  w  w .  j  a  v a2s  . c  o  m
        final Response response = call.execute();
        if (response.isSuccessful()) {
            final String content = response.body().string();
            final JSONObject head = new JSONObject(content);
            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (currencyCode.startsWith("BTC")) {
                    final String fiatCurrencyCode = currencyCode.substring(3);
                    if (!fiatCurrencyCode.equals(MonetaryFormat.CODE_BTC)
                            && !fiatCurrencyCode.equals(MonetaryFormat.CODE_MBTC)
                            && !fiatCurrencyCode.equals(MonetaryFormat.CODE_UBTC)) {
                        final JSONObject exchangeRate = head.getJSONObject(currencyCode);
                        final JSONObject averages = exchangeRate.getJSONObject("averages");
                        try {
                            final Fiat rate = parseFiatInexact(fiatCurrencyCode, averages.getString("day"));
                            if (rate.signum() > 0)
                                rates.put(fiatCurrencyCode, new ExchangeRate(
                                        new org.bitcoinj.utils.ExchangeRate(rate), BITCOINAVERAGE_SOURCE));
                        } catch (final IllegalArgumentException x) {
                            log.warn("problem fetching {} exchange rate from {}: {}", currencyCode,
                                    BITCOINAVERAGE_URL, x.getMessage());
                        }
                    }
                }
            }

            watch.stop();
            log.info("fetched exchange rates from {}, {} chars, took {}", BITCOINAVERAGE_URL, content.length(),
                    watch);

            return rates;
        } else {
            log.warn("http status {} when fetching exchange rates from {}", response.code(),
                    BITCOINAVERAGE_URL);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + BITCOINAVERAGE_URL, x);
    }

    return null;
}

From source file:com.intel.xdk.facebook.IntelXDKFacebook.java

private Bundle JSONtoBundle(JSONObject jsonObj) {
    Bundle params = new Bundle();
    Iterator<?> iter = jsonObj.keys();
    while (iter.hasNext()) {
        String key = (String) iter.next();
        String value;//from  w  w w . j a v a  2  s  .  c  om
        try {
            value = jsonObj.getString(key);
            params.putString(key, value);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return params;
}

From source file:at.alladin.rmbt.android.util.CheckSettingsTask.java

/**
* 
*//* ww  w  .  j a v  a  2s .com*/
@Override
protected void onPostExecute(final JSONArray resultList) {
    try {
        if (serverConn.hasError())
            hasError = true;
        else if (resultList != null && resultList.length() > 0) {

            JSONObject resultListItem;

            try {
                resultListItem = resultList.getJSONObject(0);

                /* UUID */

                final String uuid = resultListItem.optString("uuid", "");
                if (uuid != null && uuid.length() != 0)
                    ConfigHelper.setUUID(activity.getApplicationContext(), uuid);

                /* urls */

                final ConcurrentMap<String, String> volatileSettings = ConfigHelper.getVolatileSettings();

                final JSONObject urls = resultListItem.optJSONObject("urls");
                if (urls != null) {
                    final Iterator<String> keys = urls.keys();

                    while (keys.hasNext()) {
                        final String key = keys.next();
                        final String value = urls.optString(key, null);
                        if (value != null) {
                            volatileSettings.put("url_" + key, value);
                            if ("statistics".equals(key)) {
                                ConfigHelper.setCachedStatisticsUrl(value, activity);
                            } else if ("control_ipv4_only".equals(key)) {
                                ConfigHelper.setCachedControlServerNameIpv4(value, activity);
                            } else if ("control_ipv6_only".equals(key)) {
                                ConfigHelper.setCachedControlServerNameIpv6(value, activity);
                            } else if ("url_ipv4_check".equals(key)) {
                                ConfigHelper.setCachedIpv4CheckUrl(value, activity);
                            } else if ("url_ipv6_check".equals(key)) {
                                ConfigHelper.setCachedIpv6CheckUrl(value, activity);
                            }
                        }
                    }
                }

                /* qos names */
                final JSONArray qosNames = resultListItem.optJSONArray("qostesttype_desc");
                if (qosNames != null) {
                    final Map<String, String> qosNamesMap = new HashMap<String, String>();
                    for (int i = 0; i < qosNames.length(); i++) {
                        JSONObject json = qosNames.getJSONObject(i);
                        qosNamesMap.put(json.optString("test_type"), json.optString("name"));
                    }
                    ConfigHelper.setCachedQoSNames(qosNamesMap, activity);
                }

                /* map server */

                final JSONObject mapServer = resultListItem.optJSONObject("map_server");
                if (mapServer != null) {
                    final String host = mapServer.optString("host");
                    final int port = mapServer.optInt("port");
                    final boolean ssl = mapServer.optBoolean("ssl");
                    if (host != null && port > 0)
                        ConfigHelper.setMapServer(host, port, ssl);
                }

                /* control server version */
                final JSONObject versions = resultListItem.optJSONObject("versions");
                if (versions != null) {
                    if (versions.has("control_server_version")) {
                        ConfigHelper.setControlServerVersion(activity,
                                versions.optString("control_server_version"));
                    }
                }

                // ///////////////////////////////////////////////////////
                // HISTORY / FILTER

                final JSONObject historyObject = resultListItem.getJSONObject("history");

                final JSONArray deviceArray = historyObject.getJSONArray("devices");
                final JSONArray networkArray = historyObject.getJSONArray("networks");

                final String historyDevices[] = new String[deviceArray.length()];

                for (int i = 0; i < deviceArray.length(); i++)
                    historyDevices[i] = deviceArray.getString(i);

                final String historyNetworks[] = new String[networkArray.length()];

                for (int i = 0; i < networkArray.length(); i++)
                    historyNetworks[i] = networkArray.getString(i);

                // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////

                activity.setSettings(historyDevices, historyNetworks);

                activity.setHistoryDirty(true);

            } catch (final JSONException e) {
                e.printStackTrace();
            }

        } else
            Log.i(DEBUG_TAG, "LEERE LISTE");
    } finally {
        if (endTaskListener != null)
            endTaskListener.taskEnded(resultList);
    }
}

From source file:com.trk.aboutme.facebook.Request.java

private static void processGraphObjectProperty(String key, Object value, KeyValueSerializer serializer,
        boolean passByValue) throws IOException {
    Class<?> valueClass = value.getClass();
    if (GraphObject.class.isAssignableFrom(valueClass)) {
        value = ((GraphObject) value).getInnerJSONObject();
        valueClass = value.getClass();/*from  w  w  w. j ava2 s .  c o m*/
    } else if (GraphObjectList.class.isAssignableFrom(valueClass)) {
        value = ((GraphObjectList<?>) value).getInnerJSONArray();
        valueClass = value.getClass();
    }

    if (JSONObject.class.isAssignableFrom(valueClass)) {
        JSONObject jsonObject = (JSONObject) value;
        if (passByValue) {
            // We need to pass all properties of this object in key[propertyName] format.
            @SuppressWarnings("unchecked")
            Iterator<String> keys = jsonObject.keys();
            while (keys.hasNext()) {
                String propertyName = keys.next();
                String subKey = String.format("%s[%s]", key, propertyName);
                processGraphObjectProperty(subKey, jsonObject.opt(propertyName), serializer, passByValue);
            }
        } else {
            // Normal case is passing objects by reference, so just pass the ID or URL, if any, as the value
            // for "key"
            if (jsonObject.has("id")) {
                processGraphObjectProperty(key, jsonObject.optString("id"), serializer, passByValue);
            } else if (jsonObject.has("url")) {
                processGraphObjectProperty(key, jsonObject.optString("url"), serializer, passByValue);
            }
        }
    } else if (JSONArray.class.isAssignableFrom(valueClass)) {
        JSONArray jsonArray = (JSONArray) value;
        int length = jsonArray.length();
        for (int i = 0; i < length; ++i) {
            String subKey = String.format("%s[%d]", key, i);
            processGraphObjectProperty(subKey, jsonArray.opt(i), serializer, passByValue);
        }
    } else if (String.class.isAssignableFrom(valueClass) || Number.class.isAssignableFrom(valueClass)
            || Boolean.class.isAssignableFrom(valueClass)) {
        serializer.writeString(key, value.toString());
    } else if (Date.class.isAssignableFrom(valueClass)) {
        Date date = (Date) value;
        // The "Events Timezone" platform migration affects what date/time formats Facebook accepts and returns.
        // Apps created after 8/1/12 (or apps that have explicitly enabled the migration) should send/receive
        // dates in ISO-8601 format. Pre-migration apps can send as Unix timestamps. Since the future is ISO-8601,
        // that is what we support here. Apps that need pre-migration behavior can explicitly send these as
        // integer timestamps rather than Dates.
        final SimpleDateFormat iso8601DateFormat = new SimpleDateFormat(ISO_8601_FORMAT_STRING, Locale.US);
        serializer.writeString(key, iso8601DateFormat.format(date));
    }
}

From source file:com.hyunnyapp.easycursor.jsoncursor.JsonFieldAccessor.java

private void populateMethodList(final JSONArray array) {
    int count = 0;
    final JSONObject obj = array.optJSONObject(0);

    @SuppressWarnings("unchecked")
    final Iterator<String> keyIterator = obj.keys();
    while (keyIterator.hasNext()) {
        final String key = keyIterator.next();
        mPropertyList.add(key);//from  w w  w  .j  a  v a2  s .  c o  m
        mPropertyToIndexMap.put(key, count);
        count++;
    }
}

From source file:com.citruspay.mobile.payment.oauth2.OAuth2Token.java

public static OAuth2Token create(JSONObject json) {
    // enhance object w/ expiry date
    JSONObject jtoken = json;/*from   w  w w.  j av a  2  s  . com*/
    if (!json.has("expiry")) {
        // copy input
        jtoken = new JSONObject();
        for (Iterator<?> keys = json.keys(); keys.hasNext();) {
            String key = (String) keys.next();
            try {
                jtoken.put(key, json.get(key));
            } catch (JSONException jx) {
                throw new RuntimeException(jx);
            }
        }

        // add expiry date
        long expiry = new Date().getTime() / 1000l;
        try {
            expiry += json.getLong("expires_in");
        } catch (JSONException jx) {
            /* ignore => expires now ! */
        }
        try {
            jtoken.put("expiry", expiry);
        } catch (JSONException jx) {
            throw new RuntimeException(jx);
        }
    }

    // create token
    return new OAuth2Token(jtoken);
}

From source file:com.percolatestudio.cordova.fileupload.PSFileUpload.java

private static void addHeadersToRequest(URLConnection connection, JSONObject headers) {
    try {//from www  .j  a  va2  s.  co  m
        for (Iterator<?> iter = headers.keys(); iter.hasNext();) {
            String headerKey = iter.next().toString();
            JSONArray headerValues = headers.optJSONArray(headerKey);
            if (headerValues == null) {
                headerValues = new JSONArray();
                headerValues.put(headers.getString(headerKey));
            }
            connection.setRequestProperty(headerKey, headerValues.getString(0));
            for (int i = 1; i < headerValues.length(); ++i) {
                connection.addRequestProperty(headerKey, headerValues.getString(i));
            }
        }
    } catch (JSONException e1) {
        // No headers to be manipulated!
    }
}