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.commonsware.android.vidtry.URLHistory.java

void load(String rawJSON) throws JSONException {
    JSONObject json = new JSONObject(rawJSON);

    for (Iterator i = json.keys(); i.hasNext();) {
        String key = i.next().toString();
        HistoryItem h = new HistoryItem(key, json.getInt(key));

        spareCopy.add(h);/*from  w  ww .  j av a2  s . c o m*/
        add(h);
    }
}

From source file:org.marietjedroid.connect.MarietjeClientChannel.java

public void handleMessage(String token, JSONObject data) throws JSONException {

    System.out.println("processing" + data.toString());
    if (data.getString("type").equals("media_part")) {
        synchronized (tracksRetrieved) {
            JSONObject ding = data.getJSONObject("part");

            @SuppressWarnings("unchecked")
            Iterator<String> it = ding.keys();
            while (it.hasNext())
                tempPartialMedia.add(ding.getJSONArray((it.next().toString())));
            if (this.partialMediaSize == tempPartialMedia.size()) {
                this.partialMedia = tempPartialMedia.toArray(new JSONArray[0]);
                this.tempPartialMedia.clear();
                this.partialMediaSize = -1;
                tracksRetrieved.release();
            }/*ww w . ja  va2 s.c o m*/

        }
    } else if (data.getString("type").equals("media")) {
        synchronized (tracksRetrieved) {
            this.partialMediaSize = data.getInt("count");
            if (this.partialMediaSize == tempPartialMedia.size()) {
                this.partialMedia = tempPartialMedia.toArray(new JSONArray[0]);
                this.tempPartialMedia.clear();
                this.partialMediaSize = 0;
                tracksRetrieved.release();
            }
        }
    } else if (data.getString("type").equals("welcome"))
        return;
    else if (data.getString("type").equals("playing")) {
        this.nowPlaying = data.getJSONObject("playing");
        playingRetrieved.release();
    } else if (data.getString("type").equals("requests")) {
        this.requests = data.getJSONArray("requests");
        this.requestsRetrieved.release();

    } else if (data.getString("type").equals("error_login")) {
        synchronized (loginAttempt) {
            this.loginError = new MarietjeException(data.getString("message"));
            this.loginAttempt.release();
        }
    } else if (data.getString("type").equals("login_token")) {
        synchronized (this.loginToken) {
            this.loginToken = data.getString("login_token");
            this.loginAttempt.release();
        }
    } else if (data.getString("type").equals("logged_in")) {
        synchronized (loginAttempt) {
            this.accessKey = data.getString("accessKey");
            loginAttempt.release();
        }
    } else if (data.getString("type").equals("error_request")) {
        this.requestError = data.getString("message");
        this.requestsRetrieved.release();
    } else if (data.getString("type").equals("query_media_results")) {
        if (data.getInt("token") != server.queryToken) {
            return; // wrong result set
        }
        synchronized (this.queryResults) {
            this.queryResults.clear();
            JSONArray results = data.getJSONArray("results");
            for (int i = 0; results.opt(i) != null; i++) {
                JSONObject m = results.getJSONObject(i);
                this.queryResults.add(new MarietjeTrack(m));
            }
            this.queryResultsRetrieved.release();
        }

    }

    this.setChanged();
    this.notifyObservers(data.getString("type"));
}

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

public static void adjustConstraints(JSONObject constraints) {
    String geoPointKey = null;//from  w w  w  . j  a  v  a2s  .  c o  m
    ContainerObjectGeoPoint geoPoint = null;

    Iterator<String> iter = constraints.keys();
    while (iter.hasNext()) {
        String constraintKey = iter.next();
        Object o = constraints.get(constraintKey);
        if (o instanceof JSONObject) {
            Object nearSphere = ((JSONObject) o).opt(S_KEY);
            if (nearSphere != null && nearSphere instanceof JSONObject) {
                ContainerObject childObj = ContainerObjectFactory.getChildObject(S_KEY,
                        (JSONObject) nearSphere);
                if (childObj instanceof ContainerObjectGeoPoint) {
                    geoPointKey = constraintKey;
                    geoPoint = (ContainerObjectGeoPoint) childObj;
                    break;
                }
            }
        }
    }

    if (geoPointKey != null && geoPoint != null) {
        constraints.remove(geoPointKey);
        JSONArray geoArray = geoPoint.to2DArray();
        JSONObject nearSphereCondition = new JSONObject();
        nearSphereCondition.put(S_KEY, geoArray);
        constraints.put(ContainerObjectGeoPoint.S_GEO_POINT, nearSphereCondition);
    }
}

From source file:com.citrus.sdk.operations.OneClicksignup.java

public void savebankOption(JSONObject paymentDetails) {

    JSONObject savePayObject = new JSONObject();

    Iterator<String> key = paymentDetails.keys();

    try {//from  w w w .  jav  a2 s  . c om
        savePayObject.put("type", "netbanking").put("owner", "");
        while (key.hasNext()) {
            String keyValue = (String) key.next();
            savePayObject.put(keyValue, paymentDetails.getString(keyValue));
        }
    } catch (JSONException e) {

    }

    new SavePayOption(this.activity, savePayObject).execute();
}

From source file:com.citrus.sdk.operations.OneClicksignup.java

public void saveCardOption(JSONObject paymentDetails) {

    JSONObject savePayObject = new JSONObject();

    Iterator<String> key = paymentDetails.keys();

    try {//w  ww.jav  a2  s.co  m
        savePayObject.put("bank", "");
        while (key.hasNext()) {
            String keyValue = (String) key.next();
            savePayObject.put(keyValue, paymentDetails.getString(keyValue));
        }
    } catch (JSONException e) {

    }
    new SavePayOption(this.activity, paymentDetails).execute();
}

From source file:edu.mit.scratch.ScratchUserManager.java

public ScratchUserManager update() throws ScratchUserException {
    try {/*  w  w w .  ja  v  a 2s . com*/
        final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

        final CookieStore cookieStore = new BasicCookieStore();
        final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
        final BasicClientCookie sessid = new BasicClientCookie("scratchsessionsid",
                this.session.getSessionID());
        final BasicClientCookie token = new BasicClientCookie("scratchcsrftoken", this.session.getCSRFToken());
        final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true");
        lang.setDomain(".scratch.mit.edu");
        lang.setPath("/");
        sessid.setDomain(".scratch.mit.edu");
        sessid.setPath("/");
        token.setDomain(".scratch.mit.edu");
        token.setPath("/");
        debug.setDomain(".scratch.mit.edu");
        debug.setPath("/");
        cookieStore.addCookie(lang);
        cookieStore.addCookie(sessid);
        cookieStore.addCookie(token);
        cookieStore.addCookie(debug);

        final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build();
        CloseableHttpResponse resp;

        final HttpUriRequest update = RequestBuilder.get()
                .setUri("https://scratch.mit.edu/messages/ajax/get-message-count/")
                .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")
                .addHeader("Cookie",
                        "scratchsessionsid=" + this.session.getSessionID() + "; scratchcsrftoken="
                                + this.session.getCSRFToken())
                .addHeader("X-CSRFToken", this.session.getCSRFToken()).build();
        try {
            resp = httpClient.execute(update);
        } catch (final IOException e) {
            e.printStackTrace();
            throw new ScratchUserException();
        }

        BufferedReader rd;
        try {
            rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
        } catch (UnsupportedOperationException | IOException e) {
            e.printStackTrace();
            throw new ScratchUserException();
        }

        final StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
            result.append(line);

        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);
            final String val = "" + o;

            switch (key) {
            case "msg_count":
                this.message_count = Integer.parseInt(val);
                break;
            default:
                System.out.println("Missing reference:" + key);
                break;
            }
        }
    } catch (final Exception e) {
        e.printStackTrace();
        throw new ScratchUserException();
    }

    return this;
}

From source file:io.cslinmiso.line.utils.Utility.java

public static Map toMap(JSONObject object) throws JSONException {
    Map map = new LinkedHashMap();
    Iterator keys = object.keys();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        if (object.get(key) instanceof JSONObject || object.get(key) instanceof JSONArray) {
            map.put(key, fromJson(object.get(key)));
        } else {/*from  w  ww  .  ja  va2 s  . c  o m*/
            map.put(key, object.get(key) == null ? null : String.valueOf(object.get(key)));
        }
    }
    return map;
}

From source file:sandeep.kb.android.remote.android.AndroidWebDriver.java

private Map<Object, Object> convertJsonObjectToMap(final JSONObject json) {
    Map<Object, Object> toReturn = Maps.newHashMap();
    for (Iterator it = json.keys(); it.hasNext();) {
        String key = (String) it.next();
        try {//from   w w  w. j  av a2s.  co m
            Object value = json.get(key);
            toReturn.put(convertJsonToJavaObject(key), convertJsonToJavaObject(value));
        } catch (JSONException e) {
            throw new RuntimeException("Failed to parse JSON:" + json.toString(), e);
        }
    }
    return toReturn;
}

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

public void replaceObject(JFMongoObject refereeObject) {
    mObj.put(ContainerObjectFactory.TypeProps.__type.toString(),
            ContainerObjectFactory.TypeType.Object.toString());
    mObj.remove(Props.objectId.toString());
    JSONObject theObj = refereeObject.toJson();
    Iterator<String> keys = theObj.keys();
    while (keys.hasNext()) {
        String key = keys.next();
        mObj.put(key, theObj.get(key));// w w  w.j ava 2 s .c o m
    }
}

From source file:org.protorabbit.json.DefaultSerializer.java

@SuppressWarnings("unchecked")
void invokeMethod(Method[] methods, String key, String name, JSONObject jo, Object targetObject) {
    Object param = null;//  ww  w  . j  a  va2 s. c o m
    Throwable ex = null;
    for (int i = 0; i < methods.length; i++) {
        Method m = methods[i];
        if (m.getName().equals(name)) {
            Class<?>[] paramTypes = m.getParameterTypes();
            if (paramTypes.length == 1 && jo.has(key)) {
                Class<?> tparam = paramTypes[0];
                boolean allowNull = false;
                try {
                    if (jo.isNull(key)) {
                        // do nothing because param is already null : lets us not null on other types
                    } else if (Long.class.isAssignableFrom(tparam) || tparam == long.class) {
                        param = new Long(jo.getLong(key));
                    } else if (Double.class.isAssignableFrom(tparam) || tparam == double.class) {
                        param = new Double(jo.getDouble(key));
                    } else if (Integer.class.isAssignableFrom(tparam) || tparam == int.class) {
                        param = new Integer(jo.getInt(key));
                    } else if (String.class.isAssignableFrom(tparam)) {
                        param = jo.getString(key);
                    } else if (Enum.class.isAssignableFrom(tparam)) {
                        param = Enum.valueOf((Class<? extends Enum>) tparam, jo.getString(key));
                    } else if (Boolean.class.isAssignableFrom(tparam)) {
                        param = new Boolean(jo.getBoolean(key));
                    } else if (jo.isNull(key)) {
                        param = null;
                        allowNull = true;
                    } else if (Collection.class.isAssignableFrom(tparam)) {

                        if (m.getGenericParameterTypes().length > 0) {
                            Type t = m.getGenericParameterTypes()[0];
                            if (t instanceof ParameterizedType) {
                                ParameterizedType tv = (ParameterizedType) t;
                                if (tv.getActualTypeArguments().length > 0
                                        && tv.getActualTypeArguments()[0] == String.class) {

                                    List<String> ls = new ArrayList<String>();
                                    JSONArray ja = jo.optJSONArray(key);
                                    if (ja != null) {
                                        for (int j = 0; j < ja.length(); j++) {
                                            ls.add(ja.getString(j));
                                        }
                                    }
                                    param = ls;
                                } else if (tv.getActualTypeArguments().length == 1) {
                                    ParameterizedType type = (ParameterizedType) tv.getActualTypeArguments()[0];
                                    Class itemClass = (Class) type.getRawType();
                                    if (itemClass == Map.class && type.getActualTypeArguments().length == 2
                                            && type.getActualTypeArguments()[0] == String.class
                                            && type.getActualTypeArguments()[1] == Object.class) {

                                        List<Map<String, Object>> ls = new ArrayList<Map<String, Object>>();

                                        JSONArray ja = jo.optJSONArray(key);
                                        if (ja != null) {
                                            for (int j = 0; j < ja.length(); j++) {
                                                Map<String, Object> map = new HashMap<String, Object>();
                                                JSONObject mo = ja.getJSONObject(j);
                                                Iterator<String> keys = mo.keys();
                                                while (keys.hasNext()) {
                                                    String okey = keys.next();
                                                    Object ovalue = null;
                                                    // make sure we don't get JSONObject$Null
                                                    if (!mo.isNull(okey)) {
                                                        ovalue = mo.get(okey);
                                                    }
                                                    map.put(okey, ovalue);
                                                }
                                                ls.add(map);
                                            }
                                        }
                                        param = ls;
                                    } else {
                                        getLogger().warning(
                                                "Don't know how to handle Collection of type : " + itemClass);
                                    }

                                } else {
                                    getLogger().warning("Don't know how to handle Collection of type : "
                                            + tv.getActualTypeArguments()[0]);
                                }
                            }
                        }
                    } else {
                        getLogger().warning(
                                "Unable to serialize " + key + " :  Don't know how to handle " + tparam);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                if (param != null || allowNull) {

                    try {

                        if (m != null) {
                            Object[] args = { param };
                            m.invoke(targetObject, args);
                            ex = null;
                            break;
                        }
                    } catch (SecurityException e) {
                        ex = e;
                    } catch (IllegalArgumentException e) {
                        ex = e;
                    } catch (IllegalAccessException e) {
                        ex = e;
                    } catch (InvocationTargetException e) {
                        ex = e;
                    }
                }
            }
        }
    }
    if (ex != null) {
        if (ex instanceof RuntimeException) {
            throw (RuntimeException) ex;
        } else {
            throw new RuntimeException(ex);
        }
    }
}