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:edu.mit.scratch.ScratchUser.java

public List<ScratchProject> getFavoriteProjects(final int limit, final int offset) throws ScratchUserException {
    final List<ScratchProject> ids = new ArrayList<>();

    try {/*from  w w  w . j av  a2  s.  co m*/
        final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

        final CookieStore cookieStore = new BasicCookieStore();
        final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
        final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true");
        debug.setDomain(".scratch.mit.edu");
        debug.setPath("/");
        lang.setPath("/");
        lang.setDomain(".scratch.mit.edu");
        cookieStore.addCookie(lang);
        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://api.scratch.mit.edu/users/" + this.getUsername() + "/favorites?limit=" + limit
                        + "&offset=" + offset)
                .addHeader("Accept",
                        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                .addHeader("Referer", "https://scratch.mit.edu/users/" + this.getUsername() + "/")
                .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);
        } 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 JSONArray jsonOBJ2 = new JSONArray(result.toString().trim());

        for (int i = 0; i < jsonOBJ2.length(); i++) {
            final JSONObject jsonOBJ = jsonOBJ2.getJSONObject(i);

            final Iterator<?> keys = jsonOBJ.keys();

            while (keys.hasNext()) {
                final String key = "" + keys.next();
                final Object o = jsonOBJ.get(key);
                final String val = "" + o;

                if (key.equalsIgnoreCase("id"))
                    ids.add(new ScratchProject(Integer.parseInt(val)));
            }
        }

        return ids;
    } catch (final UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new ScratchUserException();
    } catch (final Exception e) {
        e.printStackTrace();
        throw new ScratchUserException();
    }
}

From source file:org.uiautomation.ios.server.application.LanguageDictionary.java

/**
 * // www . j  a va  2  s .  c  o m
 * @param json
 *          the json object containing all the key : value pairs for the
 *          translation of the app.
 * @return a key : value map.
 * @throws JSONException
 */
private Map<String, String> convertToMap(JSONObject json) throws JSONException {
    Map<String, String> res = new HashMap<String, String>();
    @SuppressWarnings("unchecked")
    Iterator<String> iter = json.keys();
    while (iter.hasNext()) {
        String key = iter.next();
        res.put(key, json.getString(key));
    }
    return res;
}

From source file:com.clover.sdk.v3.JsonHelper.java

public static Map toMap(JSONObject object) {
    Map map = new HashMap();
    Iterator keys = object.keys();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        map.put(key, fromJson(object.opt(key)));
    }/*  w  w w.ja  v a 2 s  .  com*/
    return map;
}

From source file:com.clover.sdk.v3.JsonHelper.java

private static Object deepCopy(Object object) {
    if (object == null) {
        return null;
    } else if (object == JSONObject.NULL) {
        return JSONObject.NULL;
    } else {/*from  w  ww.j a v  a2s.c o  m*/
        Class<?> c = object.getClass();
        if (c == JSONObject.class) {
            JSONObject src = ((JSONObject) object);
            JSONObject dst = new JSONObject();

            Iterator<String> srcKeys = src.keys();
            while (srcKeys.hasNext()) {
                String srcKey = srcKeys.next();
                try {
                    dst.put(srcKey, deepCopy(src.get(srcKey)));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }

            return dst;
        } else if (c == JSONArray.class) {
            JSONArray src = ((JSONArray) object);
            JSONArray dst = new JSONArray();

            for (int i = 0, count = src.length(); i < count; i++) {
                try {
                    dst.put(deepCopy(src.get(i)));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }

            return dst;
        } else {
            if (c == String.class || c == Long.class || c == Boolean.class || c == Integer.class
                    || c == Double.class || c == Float.class) {
                return object;
            } else {
                throw new RuntimeException("Unsupported object type: " + c.getSimpleName());
            }
        }

    }
}

From source file:org.cohorte.remote.dispatcher.beans.ParseUtils.java

/**
 * Converts a JSON object to a map//from  w  w  w . j a  v a 2s  .co m
 * 
 * @param aJSONObject
 *            A JSON object or null
 * @return A map, or null
 * @throws JSONException
 *             Error parsing the JSON object
 */
public static Map<String, Object> jsonToMap(final JSONObject aJSONObject) throws JSONException {

    if (aJSONObject == null) {
        // Nothing to do
        return null;
    }

    // Prepare the map
    final Map<String, Object> content = new LinkedHashMap<String, Object>();

    @SuppressWarnings("unchecked")
    final Iterator<String> iterator = aJSONObject.keys();
    while (iterator.hasNext()) {
        // Read the next entry
        final String key = iterator.next();
        final Object rawObject = aJSONObject.get(key);

        if (rawObject instanceof JSONObject) {
            // Got a child map
            content.put(key, jsonToMap((JSONObject) rawObject));

        } else if (rawObject instanceof JSONArray) {
            // Got a child collection
            content.put(key, jsonToList((JSONArray) rawObject));

        } else {
            // Use the read value
            content.put(key, rawObject);
        }
    }

    return content;
}

From source file:com.balch.mocktrade.finance.QuoteYahooFinance.java

public static QuoteYahooFinance fromJSONObject(JSONObject jsonObject) throws Exception {
    QuoteYahooFinance quote = new QuoteYahooFinance();
    Iterator iter = jsonObject.keys();
    while (iter.hasNext()) {
        String key = (String) iter.next();
        if (!jsonObject.isNull(key)) {
            quote.data.put(key, jsonObject.getString(key));
        }//from ww  w . j  av  a2 s. co m
    }

    String error = quote.data.get(QuoteYahooFinance.ErrorIndicationreturnedforsymbolchangedinvalid);
    if (!TextUtils.isEmpty(error)) {
        throw new Exception(error);
    }

    return quote;

}

From source file:finale.year.stage.responsable.ResponsableInterface.java

public void showThemes(JSONObject jsonObject) {
    // 1. Get Response after Sending Request to Add Theme
    // 2. Access the ThemeWindow = themeMainArea

    JSONObject response = jsonObject;

    if (response == null)
        updateStatus("Error , Null Response in ListThemes");
    //Do we have any themes Stored
    //if(!themeList.isEmpty()){
    Iterator<String> it = response.keys();
    String title = null;/*  www  .j  av a2s  .  c o  m*/
    int id = -1;
    String proposeur = null;
    String type = null;
    JSONObject jobject = null;
    log(null); //Clear Screen
    log("\n ***************** List of Themes  ******************");
    log("\n No \t ID \t Titre   \t \t \t Type  \t \t  Proposeur");
    int i = 1;
    //Iterate through List of themes
    while (it.hasNext()) {
        try {

            jobject = response.getJSONObject(it.next());

            title = jobject.getString("titre");
            proposeur = jobject.getString("email");
            type = jobject.getString("type");
            id = jobject.getInt("id");

            if (title.length() > 10)
                title = title.substring(0, 10);

            log("\n" + i + "\t " + id + "\t" + title.trim() + "\t \t \t" + type + " \t \t " + proposeur);
            i++;
        } catch (JSONException ex) {
            JOptionPane.showConfirmDialog(mainFrame, "Error Occured");
        }

    } //End of While

}

From source file:finale.year.stage.responsable.ResponsableInterface.java

public void showReclammations(JSONObject json) {
    JSONObject response = json;
    //Get reclammation Objects
    Iterator<String> it = response.keys();
    String id = null;/*from  w ww . j  av  a 2s  . c om*/
    String studentName = null;
    String studentLastN = null;
    String type = null;

    //clear screen
    log(null);

    //Display Info
    if (response == null)
        JOptionPane.showMessageDialog(mainFrame, "Error in Response");

}

From source file:org.cobaltians.cobalt.font.CobaltFontManager.java

/**
 * Returns font key:class tuples as HashMap
 * @return font key:class tuples as HashMap
 *///ww  w  .j a va 2  s . c  om
private static HashMap<String, Class<? extends CobaltAbstractFontDrawable>> getFonts() {
    HashMap<String, Class<? extends CobaltAbstractFontDrawable>> fontMap = new HashMap<>();

    try {
        // TODO: make the Cobalt method public and use it instead of reimplement it
        JSONObject configuration = getConfiguration();
        JSONObject fonts = configuration.getJSONObject(kFonts);
        Iterator<String> fontsIterator = fonts.keys();

        while (fontsIterator.hasNext()) {
            String fontName = fontsIterator.next();
            try {
                JSONObject font = fonts.getJSONObject(fontName);
                String fontClassName = font.getString(kAndroid);
                try {
                    Class<?> fontClass = Class.forName(fontClassName);
                    if (CobaltAbstractFontDrawable.class.isAssignableFrom(fontClass)) {
                        fontMap.put(fontName, (Class<? extends CobaltAbstractFontDrawable>) fontClass);
                    } else if (Cobalt.DEBUG)
                        Log.e(TAG,
                                TAG + " - getFonts: " + fontClass
                                        + " does not inherit from CobaltAbstractFontDrawable!\n" + fontName
                                        + " font message will not be processed.");

                } catch (ClassNotFoundException e) {
                    if (Cobalt.DEBUG) {
                        Log.e(TAG, TAG + " - getFonts: " + fontClassName + " class not found!\n" + fontName
                                + " font message will not be processed.");
                        e.printStackTrace();
                    }
                }
            } catch (JSONException e) {
                if (Cobalt.DEBUG) {
                    Log.e(TAG, TAG + " - getFonts: " + fontName
                            + " field is not a JSONObject or does not contain an android field or is not a String.\n"
                            + fontName + " font message will not be processed.");
                    e.printStackTrace();
                }
            }
        }
    } catch (JSONException e) {
        if (Cobalt.DEBUG) {
            Log.w(TAG, TAG + " - getFonts: fonts field of cobalt.conf not found or not a JSONObject.");
            e.printStackTrace();
        }
    }
    return fontMap;
}

From source file:com.soundcloud.playerapi.Token.java

/**
 * Construct a new token from a JSON response
 * @param json the json response/* w  w w.  ja  v a 2 s  .com*/
 * @throws IOException JSON format error
 */
public Token(JSONObject json) throws IOException {
    try {
        for (Iterator it = json.keys(); it.hasNext();) {
            final String key = it.next().toString();
            if (ACCESS_TOKEN.equals(key)) {
                access = json.getString(key);
            } else if (REFRESH_TOKEN.equals(key)) {
                // refresh token won't be set if we don't expire
                refresh = json.getString(key);
            } else if (EXPIRES_IN.equals(key)) {
                expiresIn = System.currentTimeMillis() + json.getLong(key) * 1000;
            } else if (SCOPE.equals(key)) {
                scope = json.getString(key);
            } else {
                // custom parameter
                customParameters.put(key, json.get(key).toString());
            }
        }
    } catch (JSONException e) {
        throw new IOException(e.getMessage());
    }
}